5

This is something like an infinite loop for me.

var sM = "Hello" - "World";
console.log(sM) && console.log(typeof sM);

I understand why string - string outputs NaN, but then "Hello" - "World" typeof is a number.

It means subtracting string with another string gives you a type of a number.

Where is the logic in that?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
super11
  • 436
  • 7
  • 19
  • 1
    [jQuery.isNumeric](https://api.jquery.com/jQuery.isNumeric/) does return false for NaN values. typeof only returns the internal storage mechanism for that particular variable type. In this case its stored as a number, specifically a float stored according to IEEE 754 to correspond to NaN – apokryfos May 18 '16 at 13:55
  • 1
    Why would it be a number? – Dave Newton May 18 '16 at 17:47

3 Answers3

9

why string - string outputs NaN

Because subtraction only deals in numbers, so it converts both sides to numbers and gets Not A Number.

but then "Hello" - "World" typeof is a number.

NaN has the type Number. This is standard in computing.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

Because typeof NaN is number.

It makes sense that you can't subtract 2 strings, so their subtraction is not a number (NaN).

What probably doesn't make as much sense is why NaN (not a number) is of type number. :)

See this answer for more details about the part that makes less sense.

Community
  • 1
  • 1
XCS
  • 27,244
  • 26
  • 101
  • 151
  • 1
    Also because adding a mathematical operator `-` converts whatever follows into a number? – fnune May 18 '16 at 13:39
1

Actually this is just one between many cases where javascripts operations produce results that may be unexpected to the newcomer. This happens because of implicit type coersion. Which is a type change in values that occurs automatically in certain operations where different types are involved or expected. These cases are thoroughly described in this chapter from one of the You Don't Know Js free books, here:

https://github.com/getify/You-Dont-Know-JS/blob/master/types%20&%20grammar/ch4.md

I definitively recommend this book series to every JS developer.

Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73