HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Type Operators

JavaScript provides two specific operators that help you identify what kind of data you are working with: typeof and instanceof. These are essential for writing safe code that handles different types of inputs correctly.


The typeof Operator

The typeof operator returns a string indicating the data type of an operand (a variable or a literal).

Example Resulting Type
typeof "Mim" "string"
typeof 25 "number"
typeof true "boolean"
typeof {name:'Mim'} "object"
typeof [1, 2, 3] "object" (Arrays are objects)
typeof undefined "undefined"
typeof function(){} "function"
typeof null "object" (A known JS quirk)
Important Quirk: In JavaScript, typeof null returns "object". This is considered a mistake in the original JavaScript implementation but has never been fixed to maintain compatibility with older websites.

The instanceof Operator

The instanceof operator returns true if an object is an instance of a specific object type (like a Class or a Constructor function).

const colors = ["Red", "Green", "Blue"];
const today = new Date();

console.log(colors instanceof Array);  // true
console.log(today instanceof Date);    // true
console.log(today instanceof Object);  // true (everything is an object)
console.log(colors instanceof String); // false

Why Type Operators are Needed

Because JavaScript is a dynamically typed language, a variable can hold any type of value. Type operators help you verify data before performing operations.

function processInput(data) {
    if (typeof data === "string") {
        console.log("Processing text: " + data.toUpperCase());
    } else if (typeof data === "number") {
        console.log("Processing number: " + (data * 2));
    }
}

Key Points to Remember

  • typeof is used for primitive values like strings, numbers, and booleans
  • instanceof is used for objects like Arrays, Dates, and custom classes
  • typeof null is "object" — keep this in mind when checking for null values
  • Arrays return "object" when using typeof — use Array.isArray() or instanceof to identify them correctly