typeof Operator
typeof Operator
Section titled “typeof Operator”Introduction
Section titled “Introduction”The typeof operator returns a string indicating the type of the operand. It’s the most common way to check types at runtime.
Why Do We Need This?
Section titled “Why Do We Need This?”Type checking is essential for validation, debugging, and writing type-safe code — especially since JavaScript is dynamically typed.
Visual Explanation
Section titled “Visual Explanation”flowchart TD Expression["typeof operand"] Types["Returns string"] S1["'undefined'"] S2["'boolean'"] S3["'number'"] S4["'string'"] S5["'symbol'"] S6["'bigint'"] S7["'function'"] S8["'object'"]
Expression --> Types Types --> S1 Types --> S2 Types --> S3 Types --> S4 Types --> S5 Types --> S6 Types --> S7 Types --> S8Syntax
Section titled “Syntax”typeof operand;typeof(operand); // function-like syntaxReturn Values
Section titled “Return Values”typeof undefined; // 'undefined'typeof true; // 'boolean'typeof 42; // 'number'typeof 'hello'; // 'string'typeof 123n; // 'bigint'typeof Symbol(); // 'symbol'typeof function(){}; // 'function'typeof {}; // 'object'typeof []; // 'object'typeof null; // 'object' — infamous bug!The typeof null Bug
Section titled “The typeof null Bug”typeof null; // 'object' — this is a bug from JavaScript's first release// To check for null:value === null; // use strict equalityPractical Usage
Section titled “Practical Usage”function add(a, b) { if (typeof a !== 'number' || typeof b !== 'number') { throw new Error('Both arguments must be numbers'); } return a + b;}Summary
Section titled “Summary”typeofreturns a string indicating the typetypeof nullreturns'object'(historical bug)- Arrays return
'object'— useArray.isArray()instead