Converting

A lot of data types are converted automatically.
The window.alert function will convert any value passed in to a string.


String Conversion

You can use the String function to explicitly convert a value to a string

let var1 = true; 
var1 = String(var1);
// var1 contains the value "true"

Number Conversion

You can use the Number function to explicitly convert a value to a number

let var2 = '50';  
var2 = Number(var2);
// var2 contains the value 50

let var3 = Number('this is some text'); 
// var3 contains the value NaN

Most mathematical operations convert values to numbers although the '+' operator has one exception to this rule.
If one of the values is a string then the other value is converted to a string.

let var4 = 1 + '2';  
// var4 contains '12'
let var5 = '1' + 2
// var5 contains '12'

Converting string to a number

parseFloat(text) 
parseInt(text)

something = Number(localStorage.getItem("fieldname"); 

Boolean Conversion

You can use the Boolean function to explicitly convert a value to a boolean.
The following values are converted to false:
"empty", 0, "" (empty string), undefined, NaN
Everything else becomes true




© 2020 Better Solutions Limited. All Rights Reserved. © 2020 Better Solutions Limited TopPrevNext