-1
    var x = +"5";    // 5
    alert("string to number explicitly: "+typeof x); //  number

Now consider this:

When we convert a string to a number, the result is the numeric value of a string if it is simply a number; all other strings become NaN

var y = +"foo";  //NaN
alert(typeof y); // Why this results in number?
Farhan stands with Palestine
  • 13,890
  • 13
  • 58
  • 105

2 Answers2

3

typeof NaN is as a "number" and it's expected behavior. Further information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN

Ginden
  • 5,149
  • 34
  • 68
  • 2
    The definitive reference is [*ECMA-262 §11.4.3*](http://ecma-international.org/ecma-262/5.1/#sec-11.4.3) (also see [*§4.3.20*](http://ecma-international.org/ecma-262/5.1/#sec-4.3.20)). ;-) – RobG Jan 05 '15 at 12:44
0

Its shortest form to convert a variable to number. +anything is trying to convert anything to number.

As "foo" is a string and not a valid number thus it returns NaN

Satpal
  • 132,252
  • 13
  • 159
  • 168