JavaScript tricky interview question and answer

Umar Farooque Khan
2 min readJun 7, 2023

--

JavaScript interview tricky question and answer part 2

  1. What will be the output of the following code?
console.log(2 + true);

Answer :
The output will be 3.

Explanation:

When JavaScript encounters a + operator with a number and a boolean, it automatically converts the boolean to its numeric equivalent (true becomes 1). Therefore, the expression becomes 2 + 1, which evaluates to 3.

2. What will be the output of the following code?

console.log([] == ![]);

Answer :

The output will be true.

Explanation:

This is an example of a tricky comparison involving truthy and falsy values. The ! operator negates the truthiness of an object. An empty array [] is truthy, so ![] evaluates to false. When comparing [] with false, JavaScript performs type coercion, converting false to a numeric value (0). Thus, the expression becomes [] == 0, and due to another type coercion, the empty array is converted to an empty string '', which is also converted to the numeric value 0. Hence, the expression 0 == 0 evaluates to true.

3. What will be the output of the following code?

console.log(NaN === NaN);

Answer :

The output will be false.

Explanation:

NaN (Not a Number) is a special numeric value in JavaScript, and interestingly, NaN is not equal to itself. Therefore, the expression NaN === NaN evaluates to false.

4. What will be the output of the following code?

console.log('5' - - '3');

Answer :

The output will be 8.

Explanation:

The unary - operator can be used to convert a string to a number. In this case, - '3' converts the string '3' to the number -3. Then, the expression becomes '5' - (-3), which is equivalent to '5' + 3. JavaScript performs string concatenation since one of the operands is a string, resulting in the string '53'. Finally, the result is converted to a number, yielding 8.

5. What will be the output of the following code?

console.log(null == undefined);

Answer :

The output will be true.

Explanation:

In JavaScript, null and undefined are considered equal only when using loose equality (==). Therefore, null == undefined evaluates to true.

Here are some additional high-quality tutorials for you to explore:

  1. JavaScript interview Question and Answer
  2. Node Js Interview Question and Answer
  3. JavaScript Array Interview Questions

--

--

Umar Farooque Khan
Umar Farooque Khan

Written by Umar Farooque Khan

Experienced software developer with a passion for clean code and problem-solving. Full-stack expertise in web development. Lifelong learner and team player.

Responses (5)