Type Conversions

Type Conversions

Javascript automatically converts the value depending on the occassions. Let's review the conversions

String conversions


var number1 = 123;
var string1 = number1.ToString(); // This will convert the value to "123" which is string type of value rather than integer

var boolean1 = true;
var string1 = number1.ToString(); // This will convert the value to "true" which is string type of value rather than integer
var string2 = String(boolean1); // This will convert the value to "true" which is string type of value rather than boolean

Number conversions

Numeric conversion occurs in mathematical functions and expressions automatically.

var number1 = "2" * "5" ; // 10, strings are converted to numbers

var number2 = Number("10"); // This converts string value into integer
var number2 = Number("not number"); // This converts string value into NaN
var number3 = Number(true); // This converts boolean value into integer value 1
var number4 = Number(false); // This converts boolean value into integer value 0

 

Boolean conversions

/p>

Conversion of the following values are false “empty”, like 0, an empty string, null, undefined, and NaN. Other values become true.

console.log( Boolean(1) ); // true
console.log( Boolean(0) ); // false

console.log( Boolean("hello") ); // true
console.log( Boolean("") ); // false
console.log( Boolean("0") ); // true
console.log( Boolean(" ") ); // true