Anshuman Sharma
Anshuman Sharma

Reputation: 15

Why [undefined] - 3 is -3 while undefined -3 is NaN in JavaScript?

I have been studying JavaScript lately, but I am not getting the [undefined] - x something is -x but undefined - x is NaN...

console.log(undefined-3);  //NaN
console.log([undefined]-3); // -3

Upvotes: 0

Views: 126

Answers (1)

Tafita Raza
Tafita Raza

Reputation: 331

The explanation : (Give your feedback)

Before the calculation, the compiler will try to convert "undefined" and "[undefined]" to a typeof number.

And the result is :

  • undefined => NaN. (So, "NaN - 3 = NaN")
  • [] => 0. ("0 - 3 = -3")

Check the list of JavaScript type Conversion here.

Upvotes: 2

Related Questions