Back to JavaScript Fundamentals

How to use typeof operator in JavaScript - Complete Guide with Examples

Learn how to use the typeof operator in JavaScript with practical examples. Understand how to check variable types, validate function parameters, and handle API responses using typeof.
5 min readLogan FordLogan Ford
How to use typeof operator in JavaScript - Complete Guide

What is the typeof operator in JavaScript and how does it work?

The typeof operator in JavaScript is a built-in operator that helps you determine the data type of any variable, value, or expression. It returns a string indicating the type of the unevaluated operand. Understanding typeof is crucial for writing robust JavaScript code and handling different data types effectively.


Here are all the possible return values from the typeof operator in JavaScript:

  • "number" - for numbers and NaN
  • "string" - for text and characters
  • "boolean" - for true/false values
  • "undefined" - for undefined values
  • "object" - for objects, arrays, and null
  • "function" - for functions
  • "symbol" - for unique identifiers
  • "bigint" - for large integers

You can learn more about JavaScript data types and their behaviors here.

How to use the typeof operator in JavaScript with examples

The typeof operator can be used in two different syntaxes. Let's explore both with practical examples:

1// Method 1: Using typeof as an operator
2typeof "Hello World" // Returns "string"
3typeof 42 // Returns "number"
4
5// Method 2: Using typeof as a function
6typeof("Hello World") // Returns "string"
7typeof(42) // Returns "number"

Here's a comprehensive guide showing typeof with every common data type in JavaScript:

1// Checking number types
2typeof 37 // Returns "number"
3typeof 3.14 // Returns "number"
4typeof NaN // Returns "number"
5typeof Infinity // Returns "number"
6
7// Checking string types
8typeof "" // Returns "string"
9typeof "hello" // Returns "string"
10typeof `template` // Returns "string"
11
12// Checking boolean types
13typeof true // Returns "boolean"
14typeof false // Returns "boolean"
15typeof (1 > 2) // Returns "boolean"
16
17// Checking undefined
18typeof undefined // Returns "undefined"
19typeof undeclaredVar // Returns "undefined"
20
21// Checking objects and arrays
22typeof {} // Returns "object"
23typeof [] // Returns "object"
24typeof null // Returns "object"
25typeof new Date() // Returns "object"
26
27// Checking functions
28typeof function(){} // Returns "function"
29typeof console.log // Returns "function"
30
31// Checking symbols and BigInt
32typeof Symbol() // Returns "symbol"
33typeof BigInt(123) // Returns "bigint"

Important note: A common gotcha is that typeof null returns "object". This is a known historical quirk in JavaScript that has been preserved for backward compatibility.

When and why should you use typeof in JavaScript?

The typeof operator is essential in many JavaScript programming scenarios. Here are practical examples of when and how to use it:

1// 1. Validating function parameters
2function calculateDiscount(price, percentage) {
3 if (typeof price !== "number" || typeof percentage !== "number") {
4 throw new Error("Both price and percentage must be numbers");
5 }
6 return price * (percentage / 100);
7}
8
9// 2. Safe API response handling
10function processAPIResponse(response) {
11 if (typeof response === "string") {
12 // Handle string response
13 return JSON.parse(response);
14 }
15
16 if (typeof response === "object" && response !== null) {
17 // Handle object response
18 return response;
19 }
20
21 throw new Error("Invalid API response format");
22}
23
24// 3. Type-specific data formatting
25function formatUserInput(value) {
26 switch (typeof value) {
27 case "number":
28 return value.toLocaleString();
29 case "string":
30 return value.trim();
31 case "boolean":
32 return value ? "Enabled" : "Disabled";
33 default:
34 return "Invalid input type";
35 }
36}

Common typeof operator use cases and best practices

Let's look at some simple examples of when you might want to use typeof in your code:

  1. Checking if a value is a number before doing math
  2. Making sure text input is actually text
  3. Checking if something exists before using it

Here are some beginner-friendly examples:

1// Making sure a value is a number
2function addNumbers(num1, num2) {
3 if (typeof num1 !== "number" || typeof num2 !== "number") {
4 return "Please provide numbers only";
5 }
6 return num1 + num2;
7}
8
9// Checking if input is text
10function greetUser(name) {
11 if (typeof name !== "string") {
12 return "Please provide a name as text";
13 }
14 return "Hello, " + name;
15}
16
17// Making sure something exists
18function isFeatureAvailable(feature) {
19 if (typeof feature === "undefined") {
20 return "This feature is not available";
21 }
22 return "Feature is ready to use";
23}

Troubleshooting typeof operator issues in JavaScript

Common issues and their solutions when working with typeof:

  1. Array detection: Use Array.isArray() instead of typeof
  2. Null checking: Remember typeof null returns "object"
  3. undefined vs "undefined": Use strict comparison
  4. Function detection in older browsers
1// Proper array checking
2const arr = [1, 2, 3];
3typeof arr === "object"; // true, but not specific enough
4Array.isArray(arr); // true, this is better
5
6// Proper null checking
7const value = null;
8typeof value === "object"; // true
9value === null; // true, more specific
10
11// Undefined checking
12let undeclared;
13typeof undeclared === "undefined"; // true
14undeclared === undefined; // true, but can throw error if not declared

Summary

The typeof operator is a fundamental tool in JavaScript for type checking and validation. Understanding how to use it properly can help you write more robust and error-free code. Remember to consider its quirks (like null returning "object") and use it alongside other type-checking methods when needed.


Looking for more JavaScript guides?

Check out these related articles to deepen your JavaScript knowledge:


For hands-on practice and structured learning, explore our comprehensive JavaScript Fundamentals roadmap with interactive examples and exercises.

Land your dream tech job faster

Join 810+ developers who are accelerating their coding skills with TechBlitz.

Share this article