Some JavaScript interview question topic

Mahadiul Hasan
8 min readNov 5, 2020

Truthy and falsy values

Truthy and falsy values are the non-boolean values that are coerced to true or false when performing certain operations.

The following are the only six values that are considered as falsy values in Javascript.

  • false
  • undefined
  • null
  • ""
  • NaN
  • 0

Anything that is not present in the above list is considered as truthy.

So if you are writing an if condition, you don’t need to check if something is empty or undefined or null. It will automatically be considered as false.

const value = "";
// this condition is enough and no need to check value == ""
if(value) {
console.log(value); // This code will not be executed
}const nullValue = null;
// this condition is enough and no need to check value === null
if(nullValue) {
console.log(nullValue); // This code will not be executed
}let sum;
// this condition is enough and no need to check value === undefined
if(sum) {
console.log(sum); // This code will not be executed
}

An easy way of checking if a value is truthy or falsy is by passing it to the Boolean function

Boolean(NaN) // false
Boolean([]) // true
Boolean({}) // true

You can turn any value into its truthy or falsy boolean value by flipping it twice:

let number1;
console.log(!!number1); // falseconst number2 = 10;
console.log(!!number2); // trueconst name1 = 'Tim';
console.log(!!name1); // trueconst name2 = '';
console.log(!!name2); // falseconst nullValue = null;
console.log(!!nullValue); // false

This has some practical applications.

Null Vs Undefined

null and undefined are JavaScript primitive types.

The meaning of undefined is to say that a variable has declared, but it has no value assigned.

let age //age is undefinedlet age = null //age is null

Note: accessing a variable that’s not been declared will raise a ReferenceError: <variable> is not defined error, but this does not mean it’s undefined.

How do you check if a variable is null? Use the comparison operator, for example age === null

Same for undefined: age === undefined

In both cases, you can check for:

if (!age) {}

and this will be matching both null and undefined.

You can also use the typeof operator:

let age
typeof age //'undefined'

although null is evaluated as an object, even though it is a primitive type:

let age = null
typeof age //'object'

double equal vs triple equal

We already know that == and === in JavaScript are comparison operators and are used for testing equality between two operands. Yet, they are not the same, let’s find out and understand the distinction between them.

Table of Contents

  • Triple Equals (Strict Equality Comparison)
  • Double Equals (Abstract Equality Comparison)
  • What about !== and !=
  • What Should You Use?
  • Summing Up

TRIPLE EQUALS (STRICT EQUALITY COMPARISON)

First, we examine the === operator (strict equality comparison aka identity comparison). The type of both operands must be the same as a prerequisite before performing comparisons. For example:

'hello world' === 'hello world' // true

So this comparison will return true because what we have here are the same values of the two operands, and both have the type of String.

Let’s examine another example:

2020 === 2020 // true

Here we compare 2 things with the same value, and both have the type of Number, then the result is true as anticipated.

DOUBLE EQUALS (ABSTRACT EQUALITY COMPARISON)

In JavaScript, we also can use == (abstract equality comparison, aka loose equality) to compare two values. The usage of == is slightly different compared with ===, if two operands have the same type, then it performs the comparison normally. If two values are in different types, == first converts two values in a common type, which is known as type coercion, then it conventionally compares two values.

Let’s do some examples:

5 == "5" // true

This comparison will return false if using ===. However, with ==, two values above when compared with each other will return true. JavaScript will first convert two values to a common type, then performing comparison normally, 5 compares with 5, return true.

0 == false // true

Why 0 == false gives us true. Besides two boolean values true and false, JavaScript also treats value as either truthy or falsy. Falsy values include 0, null, undefined, empty string (“”), false and NaN (not a number), all the rest are treated as truthy. The number 0 will be converted to false, Then performing comparison false == false will return true.

Implicit conversion

In JavaScript, most operators can be applied to operands of arbitrary types; at runtime, the operands will be implicitly converted to the appropriate type. For instance, the expression p in obj checks whether the object obj contains a property whose name equals the string that p evaluates to. If p does not evaluate to a string or o does not evaluate to an object, implicit conversions are performed before the check is carried out.

In many cases, however, these implicit conversions result from a typo or a misunderstanding of operator precedence rules. Even if the conversions are intentional, relying on them makes the code hard to understand.

Recommendation

Inspect the expression carefully to check whether the operands have been mistyped, and correct them if this is the case. If the conversions are intentional, consider replacing them with explicit conversions to clarify the meaning of the code.

Example

The following code intends to check whether the object obj does not contain a property of the name stored in a variable member:

function invk(obj, member) {
if (!member in obj)
throw new Error("No such member: " + member);
return obj[member]();
}

However, this test is ineffective as written: the operator ! binds more tightly than in, so it is applied first. Applying ! to a non-empty string yields false, so the in operator actually ends up checking whether obj contains a property called "false".

To fix this, parentheses should be introduced as follows:

function invk(obj, member) {
if (!(member in obj))
throw new Error("No such member: " + member);
return obj[member]();
}

As an example of the intentional use of implicit conversions, consider the following function for comparing two numbers x and y. It returns 1 if x>y, -1 if x<y, and 0 if they are equal.

function cmp(x, y) {
return (x > y) - (x < y);
}

It would be much clearer to write this out directly:

function cmp(x, y) {
if (x > y)
return 1;
if (x < y)
return -1;
return 0;
}

At the very least, the Boolean comparison results should be explicitly converted to numbers:

function cmp(x, y) {
return +(x > y) - +(x < y);
}

Apply map, filter, find on an array of objects

The map() method creates a new array with the results of calling a function for every array element.

The map() method calls the provided function once for each element in an array, in order.

let dummyArray = [{_id : 1 , name: 'John'} , {_id : 2, name: 'Smith'}, {_id : 3, name: 'James'} ,{_id : 4, name: 'Wick'} ,{_id : 5, name: 'Jennifer'} ,{_id : 2, name: 'Lorenz'}]

When we use a map in a single line with a condition it returns “Boolean” with each index of the array.
If the condition gets matched it returns True otherwise False

let result = dummyArray.map(e => e._id === 2)//output
//result: [ false, true, false, false, false, true ]

If we not give any condition and just call any particular key from an object then it gives only that particular value from an object

let result = dummyArray.map(e => e._id)//output
/* result is [1 ,2 ,3 ,4 ,5 ,2] */

look we give e.id in a condition so .map() returns only ids from all objects but if
we do not call any particular key then it returns the whole object

.Filter()

Let’s consider We have an array of objects like

let dummyArray = [{_id : 1 , name: 'John'} , {_id : 2, name: 'Smith'}, {_id : 3, name: 'James'} ,{_id : 4, name: 'Wick'} ,{_id : 5, name: 'Jennifer'} ,{_id : 2, name: 'Lorenz'}]

now suppose we have a condition that we need to get those objects whose Ids is 2

So from the above Prototypes, we should select .filter()
because .filter() function returns whole objects whose values get match

let result = dummyArray.filter(e => e._id === 2)//output
// result is [ {_id : 2, name: 'Smith'}, {_id : 2, name: 'Lorenz'}]

If we did not put any condition then Filter() returns all objects

let result = dummyArray.filter(e => e._id)//output
// result is [{_id : 1 , name: 'John'} , {_id : 2, name: 'Smith'}, //{_id : 3, name: 'James'} ,{_id : 4, name: 'Wick'} ,{_id : 5, name: //'Jennifer'} ,{_id : 2, name: 'Lorenz'}]

.Find()

Similar to .filter but it returns data of only the first index of matched condition unlike .Filter() .
purpose of .find() is to search that either data with a particular field exist or not within an array

lets demonstrate We take same dummy data like above

let dummyArray = [{_id : 1 , name: 'John'} , {_id : 2, name: 'Smith'}, {_id : 3, name: 'James'} ,{_id : 4, name: 'Wick'} ,{_id : 5, name: 'Jennifer'} ,{_id : 2, name: 'Lorenz'}]

let's consider we have a condition where we need to check that an object exists whose id is 2

We should use .find() here because it search result within an array and when require condition get a match it eventually ends the execution and returns data of that index

let result = dummyArray.find(e => e._id === 2)//output
// result is {_id : 2, name: 'Smith'}

And if we do not give any condition it returns the first index of the array

let result = dummyArray.find(e => e._id)//output
// {_id : 1 , name: 'John'}

Scope, block scope, access outer scope variable

What is Scope?

Scope determines the visibility or accessibility of a variable or other resource in the area of your code.

Global Scope

There’s only one Global scope in the JavaScript document. The area outside all the functions is considered the global scope and the variables defined inside the global scope can be accessed and altered in any other scopes.

//global scope
var fruit = 'apple'
console.log(fruit); //apple

function getFruit(){
console.log(fruit); //fruit is accessible here
}

getFruit(); //apple

Local Scope

Variables declared inside the functions become Local to the function and are considered in the corresponding local scope. Every function has its own scope. The same variable can be used in different functions because they are bound to the respective functions and are not mutually visible.

//global scope
function foo1(){
//local scope 1
function foo2(){
//local scope 2
}
}
//global scope
function foo3(){
//local scope 3
}
//global scope

Block Scope

Block scope is an area within if, switch conditions, or for and while loops. Generally speaking, whenever you see {curly brackets}, it is a block. In ES6, const and let keywords allow developers to declare variables in the block scope, which means those variables exist only within the corresponding block.

function foo(){
if(true){
var fruit1 = 'apple'; //exist in function scope
const fruit2 = 'banana'; //exist in block scope
let fruit3 = 'strawberry'; //exist in block scope
}
console.log(fruit1);
console.log(fruit2);
console.log(fruit3);
}
foo();
//result:
//apple
//error: fruit2 is not defined
//error: fruit3 is not defined

--

--