-1

I was just going through baNaNa and reached here console.log(+"")

0 I am not able to find a possible explanation.

  • 6
    Unary plus does a `toNumber()` internally. check [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_()) – Krishna Prashatt Aug 08 '19 at 09:48

1 Answers1

0

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
nick zoum
  • 6,639
  • 5
  • 26
  • 63