typeof OperatorThe typeof operator in JavaScript is used to find out the type of a value, variable, or expression. It always returns the type as a string, such as "number", "string", or "boolean".
typeof checks the type of a value at runtime."string" or "object").null and arrays.The typeof operator can return one of these strings:
"undefined""object""boolean""number""string""symbol""function""bigint"There are two common ways to use typeof:
typeof variableName
typeof (expression)
You can use typeof directly with a variable or wrap an expression in parentheses. In both cases, the result is a string.
console.log(typeof "Hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof { name: "John" }); // "object"
console.log(typeof [1, 2, 3]); // "object" (arrays are objects)
console.log(typeof null); // "object" (historical quirk)
console.log(typeof function(){}); // "function"
Here is how typeof behaves when the same variable changes type:
let x;
console.log(typeof x); // "undefined"
x = 100;
console.log(typeof x); // "number"
x = "JavaScript";
console.log(typeof x); // "string"
x = true;
console.log(typeof x); // "boolean"
x = null;
console.log(typeof x); // "object" (special case)
Arrays return "object" with typeof. To be sure a value is an array, use Array.isArray().
let arr = [1, 2, 3];
console.log(typeof arr); // "object"
console.log(Array.isArray(arr)); // true
typeof "Hello" → returns "string" because the value is text.typeof 42 → returns "number" for any numeric value (integer or decimal).typeof true → returns "boolean" for true or false.typeof undefined → returns "undefined" when a variable has no value.typeof { name: "John" } → returns "object" for plain objects.typeof [1, 2, 3] → also returns "object", because arrays are a kind of object.typeof null → returns "object" due to a historical bug in JavaScript.typeof function() {} → returns "function" for functions.undefined."string", "number", and "boolean".typeof is great for quick debugging and runtime type checking.null, use a strict comparison: x === null.Array.isArray(x) instead of typeof.typeof always returns a string like "number", not the keyword number.typeof carefully with objects; many different structures (arrays, dates, objects) all return "object".typeof 123n.typeof myFunction.null and undefined in the console.typeof returns.Array.isArray() along with typeof to compare the results for arrays.typeof on different values you use in your own code.