I was just going through baNaNa and reached here console.log(+"")
0 I am not able to find a possible explanation.
I was just going through baNaNa and reached here console.log(+"")
0 I am not able to find a possible explanation.
Using +""
is the same as using Number("")
.
It converts the string into a number.
The string is empty so the value is 0
.
console.log(+""); // 0
console.log(Number("")); // 0
console.log(+("0")); // 0
console.log(Number("0")); // 0
console.log(+"123"); // 123
console.log(Number("123")); // 123
console.log(-""); // same as `+""` but also negates the number
console.log(-"123"); // so this will be converted to a number, but also become a negative value
This way of parsing a number has a completely different behavior than parseFloat
and parseInt
. (Main difference is that Number
tries to get the numeric value of any type of variable i.e. boolea, string, number, object... whereas parseFloat
just reads the digits from a string).
console.log(parseFloat("")); // NaN
console.log(+("")); // 0
console.log(parseFloat("1st")); // 1
console.log(+("1st")); // NaN