TypeOf and Operand Conversion
The typeof operator returns a string representation of the type of the provided value.
typeof 9; // 'number'
typeof 'hello'; // 'string'
typeof []; // 'object'
typeof {}; // 'object'
typeof function(){}; // 'function'
let x = '9';
typeof x; // 'string'
To convert from one primitive type to another (i.e. string/number), there are global methods at your disposal:
-
parseInt(num);parseInt('9'); // 9 parseInt('9.999'); // 9 => note the loss of precision parseInt('hello'); // NaN parseInt(true); // NaN parseInt(false); // NaN parseInt([]); // NaN parseInt([9]); // 9 parseInt(['9']); // 9 parseInt(['9', '6']); // 9 => only parses the first index, ignoring the rest -
parseFloat(num);functions the same asparseInt()except that it preserves the precision of decimal numbers.parseFloat('9'); // 9 parseFloat('9.999'); // 9.999 -
Object.toString()'89'.toString(); // '89' 'hello'.toString(); // 'hello' 56.toString(); // SyntaxError... let num = 56; num.toString(); // '56' [].toString(); // '' [1,2,3,4].toString(); // '1,2,3,4' {}.toString(); // SyntaxError... let obj = {}; obj.toString(); // '[object Object]'