We can use the Number()
method to convert a non-number value to a number.
String to Number
A String which only contains a valid number will get converted to a Number.
Empty strings get converted to 0.
Non-empty Strings which don't contain a valid number get converted to NaN
.
Boolean to Number
true
gets converted to 1
, while false
gets converted to 0
.
Other data types to Number
null
gets converted to 0
, while undefined
gets converted to NaN
.
Calling Number()
on NaN
returns NaN
itself.