0

What will be the output of the following code, and why does the unary plus operator behave this way in JavaScript?

author
subina kallyani
hard
7
227
console.log(+true);
console.log(+"");
console.log(+null);
console.log(+undefined);
Answer
1
0
0
NaN

The unary plus operator (+) attempts to convert its operand into a number:

  1. +true → 1
     Boolean true is converted to number 1.
  2. +"" → 0
     Empty string is converted to 0.
  3. +null → 0
     null is converted to 0.
  4. +undefined → NaN
     undefined cannot be converted into a meaningful number, resulting in NaN.


Click to Reveal Answer

Tap anywhere to see the solution

Revealed

Comments0
    What will be the output of the following code, and why does the unary plus operator behave this way in JavaScript? | typecoercion | EBAT