DEV Community

Discussion on: 10 Awesome JavaScript String Tips You Might Not Know About

Collapse
 
kamcio profile image
kamcio

So you basically just want to convert string to a number?

const string = '22'
const stringToNumber = +string

console.log(stringToNumber)
// 22
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jdoe profile image
John Doe

Why does this work like this do you know?

Thread Thread
 
khuongduybui profile image
Duy K. Bui

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)