Syntax
The syntax for using the typeof operator is quite simple:
typeof operand
Here, the operand can be any variable, value, or expression. The typeof operator returns a string that represents the type of the operand.
Example:
let x = 10;
console.log(typeof x);

You can also try this code with Online Javascript Compiler
Run Code
Output:
number
In this example, the typeof operator checks the type of x, which is a number. So, it returns "number".
Real-World Examples
Let’s look at a few practical examples to understand how typeof works.
Example 1: Checking the type of a string
let name = "Alice";
console.log(typeof name);

You can also try this code with Online Javascript Compiler
Run Code
Output:
string

You can also try this code with Online Javascript Compiler
Run Code
In this case, name is a string, so typeof name returns "string".
Example 2: Checking the type of an object
let person = { name: "John", age: 25 };
console.log(typeof person);

You can also try this code with Online Javascript Compiler
Run Code
Output:
object
Here, person is an object, so typeof person returns "object".
Example 3: Checking the type of a function
function greet() {
console.log("Hello!");
}
console.log(typeof greet);

You can also try this code with Online Javascript Compiler
Run Code
Output:
function
Since greet is a function, typeof greet returns "function".
Primitive Data Types
In JavaScript, there are six primitive data types: number, string, boolean, undefined, null, and symbol. The typeof operator helps identify these types.
- Number: Represents numeric values.
let age = 25;
console.log(typeof age);

You can also try this code with Online Javascript Compiler
Run Code
Output:
number
2. String: Represents text values.
let name = "John";
console.log(typeof name);

You can also try this code with Online Javascript Compiler
Run Code
Output:
string
3. Boolean: Represents true or false.
let isActive = true;
console.log(typeof isActive);
Output:
boolean
4. Undefined: Represents a variable that has been declared but not initialized.
let something;
console.log(typeof something);
Output:
undefined
5. Null: Represents the absence of a value.
let data = null;
console.log(typeof data);
Output:
object
(Note: This is a peculiar behavior in JavaScript, where typeof null incorrectly returns "object").
6. Symbol: A unique and immutable value used for object property keys.
let sym = Symbol('description');
console.log(typeof sym);
Output:
symbol
How to Recognize an Array?
The typeof operator is useful for determining the type of a value, but it has a peculiarity when it comes to arrays. When you apply the typeof operator to an array, it returns "object" instead of "array". This behavior can be confusing since arrays are technically objects in JavaScript.
For example:
let fruits = ["apple", "banana", "orange"];
console.log(typeof fruits); // Output: "object"
As you can see, despite `fruits` being an array, the typeof operator returns "object". To accurately check if a value is an array, you can use the `Array.isArray()` method instead.
let fruits = ["apple", "banana", "orange"];
console.log(Array.isArray(fruits)); // Output: true
The `Array.isArray()` method specifically checks if the passed value is an array and returns `true` if it is, and `false` otherwise.
The instanceof Operator
Another way to check if a value is an array or belongs to a specific object type is by using the `instanceof` operator. The `instanceof` operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
For example:
let fruits = ["apple", "banana", "orange"];
console.log(fruits instanceof Array); // Output: true
In this case, the `instanceof` operator checks if `fruits` is an instance of the `Array` constructor and returns `true` since it is indeed an array.
The `instanceof` operator can also be used to check if an object belongs to a specific class or constructor function.
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
}
let myCar = new Car("Honda", "Civic");
console.log(myCar instanceof Car); // Output: true
In this example, `myCar` is an instance of the `Car` class, so `myCar instanceof Car` evaluates to `true`.
Undefined Variables
In JavaScript, when you declare a variable without assigning it a value, or when you try to access a variable that has not been declared, its value is `undefined`. The typeof operator returns "undefined" for such variables.
For example:
let myVariable;
console.log(typeof myVariable); // Output: "undefined"
console.log(typeof undeclaredVariable); // Output: "undefined"
In the first case, `myVariable` is declared but not assigned a value, so its value is `undefined`. In the second case, `undeclaredVariable` is not declared at all, but the typeof operator still returns "undefined".
It's important to note that accessing an undeclared variable will throw a `ReferenceError` at runtime, but the typeof operator does not throw an error and returns "undefined" instead.
console.log(undeclaredVariable); // Throws ReferenceError: undeclaredVariable is not defined
To avoid such errors, it's a good practice to always declare variables before using them and assign a default value if necessary.
Empty Values
In JavaScript, there are several ways to represent empty or falsy values. These include `null`, an empty string (`""`), `0`, `false`, `undefined`, and `NaN`. When you apply the typeof operator to these values, it returns different results.
Let’s take a look at some examples:
console.log(typeof null); // Output: "object"
console.log(typeof ""); // Output: "string"
console.log(typeof 0); // Output: "number"
console.log(typeof false); // Output: "boolean"
console.log(typeof undefined); // Output: "undefined"
console.log(typeof NaN); // Output: "number"
As you can see, the typeof operator returns the corresponding data type for each empty value, except for `null`. Despite representing an empty value, the typeof operator returns "object" for `null`, which is considered a longstanding bug in JavaScript.
It's important to be aware of these empty values and their types when working with JavaScript, as they can sometimes lead to unexpected behavior if not handled properly.
Null
`null` is a special value in JavaScript that represents a deliberate non-value or absence of any object value. It is often used to explicitly clear or reset a variable.
For example:
let myVariable = null;
console.log(typeof myVariable); // Output: "object"
As mentioned earlier, the typeof operator returns "object" for `null`, which is considered a bug in JavaScript. This behavior exists for historical reasons and cannot be fixed without breaking existing code.
To properly check if a value is `null`, you can use the strict equality operator (`===`):
let myVariable = null;
console.log(myVariable === null); // Output: true
By using the strict equality operator, you can differentiate between `null` and other falsy values like `undefined`.
Limitations
While typeof is a useful operator, it has some limitations.
The typeof returns "object" for both objects and arrays, which can be confusing.
let arr = [1, 2, 3];
console.log(typeof arr);

You can also try this code with Online Javascript Compiler
Run Code
Output:
object
Even though arr is an array, typeof arr returns "object". To accurately check if a variable is an array, we can use Array.isArray().
console.log(Array.isArray(arr));
Output:
true
Null: As mentioned earlier, typeof null incorrectly returns "object", which is a known issue in JavaScript.
Browser Compatibility
The typeof operator is supported in all major browsers, including Chrome, Firefox, Safari, Opera, and Internet Explorer. It has been a part of JavaScript since the early versions of the language and is widely used for type checking.
However, there are a few caveats to keep in mind when using the typeof operator:
1. The behavior of typeof null returning "object" is consistent across browsers, as it is defined in the ECMAScript specification.
2. In older versions of Internet Explorer (IE 8 and below), the typeof operator returns "object" for both null and undefined. This is a known issue specific to those versions of IE.
3. When using the typeof operator with undeclared variables, modern browsers return "undefined" without throwing an error. However, in older browsers (IE 8 and below), it may throw a ReferenceError.
Common Use Cases of typeof in JavaScript
1. Type Checking in Conditional Statements: You can use typeof to perform type checking inside if statements to ensure that you are working with the expected type.
let input = "Hello, World!";
if (typeof input === "string") {
console.log("Input is a string");
}
2. Type Safety: typeof is useful for ensuring type safety when working with dynamic types, especially when you are handling user inputs.
function add(a, b) {
if (typeof a !== "number" || typeof b !== "number") {
throw new Error("Both arguments must be numbers");
}
return a + b;
}
console.log(add(2, 3));
console.log(add("2", 3));

You can also try this code with Online Javascript Compiler
Run Code
Output:
5
Throws error
3. Debugging: typeof is commonly used in debugging to check variable types and ensure that your program behaves as expected.
let someVar = { key: "value" };
console.log(typeof someVar);

You can also try this code with Online Javascript Compiler
Run Code
Output:
object
Frequently Asked Questions
What is the output of typeof null in JavaScript?
typeof null returns "object". This is a quirk in JavaScript, and it's important to be aware of it when working with data types.
Can I use typeof to check if a variable is an array?
No, typeof returns "object" for arrays. To check if a variable is an array, use Array.isArray(variable).
Is typeof a reliable way to check variable types?
Yes, typeof is generally reliable for primitive data types. However, it has limitations with objects, arrays, and null.
Conclusion
In this article, we discussed the syntax, examples, primitive data types, limitations, browser compatibility, and common use cases of the typeof operator. The typeof operator is an essential tool in JavaScript for identifying the type of a variable or value. By using it, we can ensure our program behaves as expected and handle different data types correctly. Understanding typeof will help you write more efficient and error-free JavaScript code.