0

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
  • Because JavaScript is weird. – luk2302 Jan 24 '23 at 07:35
  • 2
    You could take a test like https://jsisweird.com/ and there are the answers that you are looking for. Like luk2302 said. JS is weird :) – Rafał Figura Jan 24 '23 at 07:43
  • https://stackoverflow.com/questions/68632168/coercing-an-array-of-length-1-to-a-number – Jan Pfeifer Jan 24 '23 at 07:46
  • @luk2302 more weird than somebody trying to subtract an integer from an array? What would you consider a "non-weird" result of that? And how many would agree with you and wouldn't want a different result? Here are a few options to pick from: 1. apply the subtraction to each item in the array: `[3, 4, 5] - 3` -> `[0, 1, 2]` 2. reduce the length of the array: `[1, 2, 3, 4] - 3` -> `[1]`. 3. the result is `NaN` because the operation is nonsensical. 4. the result is `undefined` because the operation is nonsensical. 5. there is an error because the operation is nonsensical. – VLAZ Jan 24 '23 at 08:05
  • @VLAZ 5........ – luk2302 Jan 24 '23 at 09:58

1 Answers1

2

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.

Tafita Raza
  • 206
  • 2
  • 4