JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS Typeof


In JavaScript, understanding the type of a value is just as important as working with the value itself. The typeof operator is a built-in tool that helps you identify the data type of a variable or expression at runtime. Since JavaScript is a dynamically typed language, variables can hold different types of values at different times. The typeof operator becomes especially useful in such situations to avoid unexpected behavior and bugs.

In this chapter, you will learn what the typeof operator is, why it is important, how it works with different data types, practical examples, common misunderstandings, best practices, and real-world use cases.

What Is the typeof Operator

The typeof operator returns a string that indicates the type of the operand. It can be used with variables, literals, expressions, and even function calls.

typeof value

or

typeof(value)

Both forms are valid and widely used. The result is always a string such as "number", "string", or "boolean".

Why typeof Is Important

Because JavaScript automatically assigns types to variables, the type of a variable can change during execution. Checking types helps you ensure that your code behaves as expected.

Using typeof helps you:

  • Validate user input

  • Prevent runtime errors

  • Write flexible and reusable functions

  • Handle optional or dynamic values safely

  • Debug issues related to unexpected data types

Using typeof with Primitive Data Types

typeof with Number

When typeof is used with numeric values, it returns "number".

let ageAnanya = 22;
let heightMira = 5.4;

console.log(typeof ageAnanya); // number
console.log(typeof heightMira); // number

Even special numeric values return "number".

console.log(typeof Infinity); // number
console.log(typeof NaN);      // number

typeof with String

Strings always return "string", regardless of how they are defined.

let firstName = "Ishita";
let city = 'Patna';

console.log(typeof firstName); // string
console.log(typeof city);      // string

typeof with Boolean

Boolean values return "boolean".

let isLoggedIn = true;
let hasAccess = false;

console.log(typeof isLoggedIn); // boolean
console.log(typeof hasAccess);  // boolean

typeof with Undefined

If a variable is declared but not assigned a value, typeof returns "undefined".

let score;
console.log(typeof score); // undefined

This also works safely even if a variable has not been declared at all.

console.log(typeof notDeclared); // undefined

This behavior prevents reference errors in many situations.

typeof with Null

One of the most confusing results in JavaScript is when typeof is used with null.

let selectedCourse = null;
console.log(typeof selectedCourse); // object

Although null represents an empty or intentional absence of value, typeof null returns "object". This is a known behavior in JavaScript and should be handled carefully.

typeof with BigInt

The BigInt data type returns "bigint" when checked using typeof.

let bigNumber = 12345678901234567890n;
console.log(typeof bigNumber); // bigint

typeof with Symbol

Symbols return "symbol".

let uniqueId = Symbol("id");
console.log(typeof uniqueId); // symbol

Using typeof with Non-Primitive Data Types

typeof with Object

Objects return "object" when checked using typeof.

let student = {
    name: "Sanya",
    age: 21
};

console.log(typeof student); // object

Arrays also return "object", which can be confusing for beginners.

let students = ["Ananya", "Ishita", "Mira"];
console.log(typeof students); // object

To specifically check for an array, additional methods are needed.

typeof with Function

Functions return "function", which is a special case in JavaScript.

function greet(name) {
    return "Hello " + name;
}

console.log(typeof greet); // function

This allows you to check whether a variable is callable before invoking it.

Practical Examples

Example 1: Type Checking Before Calculation

function addNumbers(a, b) {
    if (typeof a === "number" && typeof b === "number") {
        return a + b;
    }
    return "Invalid input";
}

console.log(addNumbers(10, 20)); 
console.log(addNumbers("10", 20));

Example 2: Validating User Input

let userAge = "22";

if (typeof userAge === "string") {
    userAge = Number(userAge);
}

console.log(typeof userAge); // number

Example 3: Handling Optional Values

function greetUser(name) {
    if (typeof name === "undefined") {
        return "Hello Guest";
    }
    return "Hello " + name;
}

console.log(greetUser("Riya"));
console.log(greetUser());

Example 4: Checking Function Existence

let callback = function () {
    return "Task completed";
};

if (typeof callback === "function") {
    console.log(callback());
}

Common Misunderstandings

  • Assuming typeof null returns "null"

  • Expecting arrays to return "array"

  • Using typeof as the only method to detect objects

  • Forgetting that NaN is still a number

Best Practices

  • Use typeof for basic type checking

  • Combine typeof with other checks for arrays and null values

  • Always compare the result of typeof with a string

  • Use type checks in functions that accept dynamic input

Real-World Use Cases

The typeof operator is widely used in real-world applications:

  • Form validation to check input types

  • API response validation

  • Safely handling optional function parameters

  • Building utility functions that work with multiple data types

  • Debugging issues related to unexpected values

Summary of JS Typeof

The typeof operator in JavaScript is a powerful and simple tool for identifying the type of a value at runtime. It works with all primitive and non-primitive data types and helps prevent errors caused by incorrect assumptions about data. While it has some known quirks, such as returning "object" for null and arrays, understanding these behaviors allows you to use typeof effectively. Mastering typeof is essential for writing safe, flexible, and robust JavaScript code.


Practice Questions

Q1. How do you check the data type of the string "Welcome" using the typeof operator?

Q2. How do you find the type of a variable isOnline = true?

Q3. What will typeof 100 return, and how do you use it in a console log statement?

Q4. How do you check the type of an undefined variable let result; using typeof?

Q5. What does typeof null return, and why is it considered a JavaScript bug?

Q6. How do you use typeof to check if a function myFunc is of type "function"?

Q7. How do you determine if an array let colors = ["red", "blue"] is an object using typeof?

Q8. How do you use typeof to check the type of a BigInt value 123456789n?

Q9. How do you store the result of typeof in a variable and print it?

Q10. How do you check the type of a symbol declared as let sym = Symbol("key")?


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top