Open In App

JavaScript typeof Operator

Last Updated : 13 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The typeof operator in JavaScript is used to determine the data type of a value or variable. It returns a string indicating the type, such as “string”, “number”, “boolean”, “object”, etc.

JavaScript
console.log(typeof "Hello");
console.log(typeof 42);     
console.log(typeof true);
console.log(typeof {});      
console.log(typeof undefined); 

Output
string
number
boolean
object
undefined

Key Points:

  • Always outputs the data type as a string.
  • Can be used anywhere without imports or dependencies.
  • Determines the type of literals, variables, and expressions.
  • Special Cases:
    • typeof null returns “object” (a known quirk).
    • Functions return “function” instead of “object”.
  • Useful for checking types in dynamic or untyped environments.

Syntax:

typeof operand
  • operand: The value or variable to check.

Real-World Examples

Example 1: Validating User Input

JavaScript
function fun(input) {
    if (typeof input === "number") {
        console.log("Valid number provided!");
    } else {
        console.log("Please provide a number.");
    }
}
fun(42);
fun("Hi"); 

Output
Valid number provided!
Please provide a number.

Example 2: Dynamic Property Access

JavaScript
const settings = { darkMode: true };
if (typeof settings.darkMode === "boolean") {
    console.log("Dark mode setting is valid.");
}

Output
Dark mode setting is valid.

Primitive Data Types

Primitive data types in JavaScript are basic data types that represent single values. They include:

Data TypeDescription
NumberRepresents numeric values like integers and floating-point numbers.
StringRepresents textual data enclosed within single quotes (”) or double quotes (“”).
BooleanRepresents true or false values.
UndefinedRepresents a variable that has been declared but has not been assigned a value.
NullRepresents the intentional absence of any object value.
SymbolRepresents a unique and immutable data type used as the key of an object’s property.
BigIntRepresents large integers beyond the limit of the Number type.

Limitations

  • typeof null returns “object”, which is misleading and a legacy bug in JavaScript.
  • Cannot distinguish between arrays and objects (typeof [] is “object”).
  • Cannot differentiate between classes or specific object types.
  • typeof NaN returns “number”, though it’s technically “not a number.”


Next Article
Article Tags :

Similar Reads