Home » JavaScript typeof Operator Tutorial with Examples

JavaScript typeof Operator Tutorial with Examples

The typeof operator in JavaScript is used to determine the data type of a variable or expression.

It returns a string that indicates the type of the operand, making it useful for debugging, validation, or writing code that handles different data types flexibly.

In this tutorial, you'll learn:

What is the typeof operator?
Syntax and basic usage of typeof
Common data types returned by typeof
Practical examples of using typeof
Important edge cases with typeof

1. What is the typeof Operator?

The typeof operator is a built-in JavaScript operator used to check the type of a variable or expression. It returns a string indicating the type of the value passed to it.

It is useful for performing type checking when writing conditional logic or debugging your code.

2. Syntax and Basic Usage of typeof

The syntax of the typeof operator is simple and can be used in two forms:

Prefix notation: Placing typeof before a variable or value.
Parentheses notation: typeof()—using parentheses to enclose the operand, although this is not required.
Syntax:

typeof operand;

operand: The variable or expression whose type you want to check.

Example 1: Basic Usage of typeof

let greeting = "Hello, World!";
let age = 30;

console.log(typeof greeting);  // Output: 'string'
console.log(typeof age);  // Output: 'number'

In this example:

typeof greeting returns ‘string' because the value of greeting is a string.
typeof age returns ‘number' because the value of age is a number.

3. Common Data Types Returned by typeof

The typeof operator can return the following values:

string: For strings, like “Hello”.
number: For numbers, both integers and floating-point numbers, like 42 or 3.14.
boolean: For true or false.
undefined: For variables that have been declared but not assigned a value.
object: For objects, arrays, null, and other non-primitive data types.
function: For functions.
symbol: For symbols introduced in ES6.

Example 2: Checking Different Data Types

let name = "Alice";
let age = 25;
let isStudent = true;
let user = { name: "Alice", age: 25 };
let colors = ["red", "green", "blue"];
let sayHello = function() { return "Hello"; };
let symbol = Symbol("id");

console.log(typeof name);      // Output: 'string'
console.log(typeof age);       // Output: 'number'
console.log(typeof isStudent); // Output: 'boolean'
console.log(typeof user);      // Output: 'object'
console.log(typeof colors);    // Output: 'object'
console.log(typeof sayHello);  // Output: 'function'
console.log(typeof symbol);    // Output: 'symbol'

Objects and arrays both return ‘object' because they are object types in JavaScript.
Functions return ‘function', which is a specific subtype of object.
Symbols are a unique and primitive data type, introduced in ES6, and return ‘symbol'.

4. Practical Examples of Using typeof

Example 3: Type Checking in Conditional Statements

You can use the typeof operator to validate variable types in conditional logic.

let input = 42;

if (typeof input === 'number') {
    console.log("The input is a number.");
} else if (typeof input === 'string') {
    console.log("The input is a string.");
} else {
    console.log("The input is of a different type.");
}
// Output: The input is a number.

In this example:

typeof is used to check whether input is a number or a string. The conditional logic ensures that the correct message is logged.

Example 4: Checking for undefined Variables

The typeof operator is commonly used to check if a variable has been declared or initialized.

let variable;

if (typeof variable === 'undefined') {
    console.log("The variable is undefined.");
}
// Output: The variable is undefined.

Here, typeof variable returns ‘undefined' because variable was declared but not initialized.

Example 5: Checking for Functions

The typeof operator can be used to check if a variable is a function before calling it.

let maybeFunction = function() { return "I am a function"; };

if (typeof maybeFunction === 'function') {
    console.log(maybeFunction());  // Output: I am a function
}

This ensures that the code checks if the variable is a function before invoking it.

5. Important Edge Cases with typeof

While typeof is a helpful tool, there are some edge cases to be aware of:

5.1. typeof null Returns ‘object'

One of the well-known quirks of JavaScript is that typeof null returns ‘object', even though null is considered a primitive type.

let value = null;
console.log(typeof value);  // Output: 'object'

This is a historical bug in JavaScript but has been retained for backward compatibility.

5.2. typeof on Arrays Returns ‘object'

In JavaScript, arrays are technically objects, so typeof returns ‘object' for arrays. You can use Array.isArray() to specifically check for arrays.

let colors = ["red", "green", "blue"];
console.log(typeof colors);  // Output: 'object'
console.log(Array.isArray(colors));  // Output: true

5.3. typeof for Uninitialized Variables

When a variable is declared but not assigned a value, typeof will return ‘undefined'.

let uninitialized;
console.log(typeof uninitialized);  // Output: 'undefined'

5.4. typeof NaN Returns ‘number'

NaN (Not-a-Number) is a special value representing an invalid number, but typeof NaN returns ‘number'.

let invalidNumber = NaN;
console.log(typeof invalidNumber);  // Output: 'number'

Conclusion

The typeof operator is a simple but powerful tool for checking the data types of variables and expressions in JavaScript. Here's a summary of what you've learned:

The typeof operator returns the type of a variable or expression as a string.
Common data types returned by typeof include ‘string', ‘number', ‘boolean', ‘undefined', ‘object', ‘function', and ‘symbol'.
Edge cases include typeof null returning ‘object', arrays being reported as ‘object', and NaN being reported as ‘number'.

By using the typeof operator effectively, you can write more flexible and error-free JavaScript code!

You may also like