+ 2
[SOLVED] JavaScript: var x = +y
var y = "John"; var x = +y console.log(typeof(x)); Why is x a number? (found in a SoloLearn challenge)
7 Answers
+ 4
Hi! Look for information about what a unary plus does with a variable (string in your case) and what type of special value NaN has
+ 3
NaN - Not a Number
NaN is a JavaScript reserved word indicating that a number is not a legal number.
Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number)
https://www.w3schools.com/js/js_numbers.asp
NaN is a number: typeof NaN returns number. You must remember it!
+ 2
You can convert a string to intiger by that way.
Ex: var x= promt("Input") ;
// input 12, now x contain string type "12"
var x = +x;
//now x Contains Integer number 12
This is equalent to
var x= Number(promt("Input") ;
Edit:
in your example, as Ярослав Вернигора(Yaroslava) pointed below,
y= "john" will not possible to convert to equalent Number so result a NaN (Not a Number).
NaN type also a Number. So type of x is Number.
Thank you.. Ярослав Вернигора(Yaroslav Vernigora) for the point, I added correction....
+ 2
Jayakrishna🇮🇳 Thats right, but he has in "y" string "John". Then it tries to apply a unary plus to this line and write the result in "x"
+ 2
it tries to convert a non-numeric value to a number. the result is NaN. And NaN is... a number! 😁 This is a JavaScript 😂
+ 1
Ярослав Вернигора(Yaroslav Vernigora)
Yes. But he is asking for only "typeof" x.
So Prof. Dr. Zoltán Vass it is about typeof explanation only.. How x type is a number not a string of the statements.
Edit:
If am wrong correct me....
@Ярослав Вернигора(Yaroslav Vernigora)
+ 1
I'm guessing he was expecting to have "john" added to x, which would likely be something more like x += y, based on what I from java. Likely, the plus wouldn't even be necessary for that; just an x = y would do that. Without x being given a value, I'm not certain what "x = x + y" would result in in this language.