Type Checking
To check a variable’s type, you can use the typeof
operator:
console.log(typeof 42); // Outputs: 'number'
console.log(typeof 'hello'); // Outputs: 'string'
console.log(typeof true); // Outputs: 'boolean'
console.log(typeof undefined); // Outputs: 'undefined'
console.log(typeof null); // Outputs: 'object' (This is actually a historical bug in JavaScript!)
console.log(typeof {}); // Outputs: 'object'
console.log(typeof []); // Outputs: 'object' (Arrays are special objects)
console.log(typeof function(){}); // Outputs: 'function'
number
string
boolean
undefined
object
object
object
function
Type Coercion
One of JavaScript’s most distinctive features is automatic type coercion - converting values from one type to another:
console.log('5' + 3); // Outputs: '53' (number converted to string)
console.log('5' - 3); // Outputs: 2 (string converted to number)
console.log('5' * '3'); // Outputs: 15 (both strings converted to numbers)
console.log(true + 1); // Outputs: 2 (true is converted to 1)
String to Number
// String to Number
let numStr = '42.5';
let num1 = Number(numStr); // 42
console.log(num1); // Outputs: 42.5
let num2 = parseInt(numStr); // 42
console.log(num2); // Outputs: 42
let num3 = parseFloat('3.14'); // 3.14
console.log(num3); // Outputs: 3.14
let num4 = +'42'; // 42 (using the unary + operator)
console.log(num4); // Outputs: 42
Number to String
// Number to String
let strNum = String(42); // '42'
console.log(strNum); // Outputs: '42'
typeof strNum; // Outputs: 'string'
let strNum2 = 42 + ''; // '42' (using string concatenation)
console.log(strNum2); // Outputs: '42'
let strNum3 = 34
strNum3.toString(); // '34' (using the toString method)
To boolean
// To Boolean
let bool1 = Boolean(1); // true
let bool2 = Boolean(0); // false
let bool3 = !!42; // true (using double negation)