Because + operator tells JavaScript to wrap both sides of it with Number(). Left side here is blank, so Number() gives you 0. Right side here is "22", so Number("22") gives you 22. Then + operator adds these 2 Numbers together and gives you 22.
That's a lazy way to convert a String to a Number.
The explicit equivalent way is const stringToNumber = Number(string).
However, if you need more fine-tuned control over the parsing of the string, consider using parseInt or parseFloat (which lets you parse number representation in bin, oct, hex, etc., not just dec)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Why does this work like this do you know?
Because
+
operator tells JavaScript to wrap both sides of it withNumber()
. Left side here is blank, soNumber()
gives you 0. Right side here is "22", soNumber("22")
gives you 22. Then+
operator adds these 2Number
s together and gives you 22.That's a lazy way to convert a String to a Number.
The explicit equivalent way is
const stringToNumber = Number(string)
.However, if you need more fine-tuned control over the parsing of the string, consider using parseInt or parseFloat (which lets you parse number representation in bin, oct, hex, etc., not just dec)