Home Courses Type Operators Explained - typeof, instanceof, in

Type Operators Explained - typeof, instanceof, in

Type operators are used to check the data type of a variable or value.


Why we use them:

  1. When data is dynamic (comes from user input, API, etc.)
  2. When variable values change multiple times
  3. To avoid bugs by confirming data type


Types of Type Operators

There are 3 main type operators in JavaScript:

  1. typeof
  2. instanceof
  3. in


typeof Operator

Purpose:

Used to check the data type of a variable

Syntax:


typeof variable


Examples:


let data = "Anil";
console.log(typeof data); // string

data = 123;
console.log(typeof data); // number

data = true;
console.log(typeof data); // boolean


Important Cases

Undefined


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


Null (Important Interview Question)


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

Note:

  1. This is a JavaScript bug
  2. Actual type should be null, but it returns object


NaN


let data = NaN;
console.log(typeof data); // number

Note:

  1. NaN means "Not a Number"
  2. But its type is still number


Array


let data = [];
console.log(typeof data); // object

Note:

  1. Arrays are treated as objects


Function


let data = function() {};
console.log(typeof data); // function


Common Mistake


let data = "123";
console.log(typeof data); // string

Even though it looks like a number, it is a string because of quotes.


in Operator

Purpose:

Used to check if a property exists inside an object

Syntax:


"key" in object


Example:


let user = {
name: "Anil",
age: 29,
email: "anil@test.com"
};

console.log("name" in user); // true
console.log("phone" in user); // false


instanceof Operator

Purpose:

Used to check if an object belongs to a specific class (constructor)

Syntax:


object instanceof Class


Example 1: Array


let info = [];
console.log(info instanceof Array); // true
console.log(info instanceof Object); // true


Example 2: Date


let info = new Date();

console.log(info instanceof Date); // true
console.log(info instanceof Array); // false

Key Points:

  1. Arrays are also objects → so both can return true
  2. Works with:
  3. Array
  4. Object
  5. Date
  6. Custom classes (later topic)


Quick Summary Table

Operator
typeofCheck data type"string", "number"
inCheck property in objecttrue / false
instanceofCheck object belongs to classtrue / false


Important Interview Questions

  1. What is typeof null?
  2. Answer: "object" (JavaScript bug)
  3. What is typeof NaN?
  4. Answer: "number"
  5. Is array an object?
  6. Yes, typeof [] → object
  7. Difference between typeof and instanceof?
  8. typeof → gives type
  9. instanceof → checks class/constructor


Final Understanding

  1. Use typeof → for basic type checking
  2. Use in → for checking object keys
  3. Use instanceof → for checking object type/class


Share this lesson: