console.log(typeof(30 + 'years'));//string
console.log(Number(30 + 'years')); //NaN
This function only works for base 10 integers and does not allow trailing characters. The conversion may not have worked since it was an impossible one, but this function does work where allowed. for example, conversion of a boolean to a number;
console.log(Number(true)); //1 console.log(Number(false)); //0
2) String() / toString()
- String() method attempts to convert the type into a string. Examples;
console.log(typeof(true)); //boolean console.log(typeof(String(true))); //string console.log(typeof(1)); //number console.log(typeof(String(1))); //string console.log(typeof(true)); //boolean console.log(typeof(true.toString())); //string
- When using the toString() method the conversion is always in base 10, but if we specify the argument, we can convert into other bases between 2 and 36. Examples;
let age = 100; console.log(age.toString(2)); //1100100 console.log(age.toString(8)); //144 console.log(age.toString(16)); //64
Apart from null and undefined, all the other types can use the toString() method.
let number = null; number.toString(); console.log(number); //Cannot read property 'toString' of null let text; text.toString(); console.log(number); //Cannot read property 'toString' of undefined
- Boolean() method attempts to convert the type into boolean. Examples;
console.log(typeof(1)); //number console.log(typeof(Boolean(1))); //true - boolean console.log(typeof(0)); //number console.log(typeof(Boolean(0))); //false - boolean console.log(Boolean('hello')); //true - boolean console.log(Boolean('')); //false- boolean
Until the next article, KEEP CODING & SHARING.