Type Operators Explained - typeof, instanceof, in
Type operators are used to check the data type of a variable or value.
Why we use them:
- When data is dynamic (comes from user input, API, etc.)
- When variable values change multiple times
- To avoid bugs by confirming data type
Types of Type Operators
There are 3 main type operators in JavaScript:
typeofinstanceofin
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:
- This is a JavaScript bug
- Actual type should be
null, but it returnsobject
NaN
let data = NaN;
console.log(typeof data); // number
Note:
NaNmeans "Not a Number"- But its type is still
number
Array
let data = [];
console.log(typeof data); // object
Note:
- 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:
- Arrays are also objects → so both can return true
- Works with:
- Array
- Object
- Date
- Custom classes (later topic)
Quick Summary Table
| Operator | ||
typeof | Check data type | "string", "number" |
in | Check property in object | true / false |
instanceof | Check object belongs to class | true / false |
Important Interview Questions
- What is
typeof null? - Answer:
"object"(JavaScript bug) - What is
typeof NaN? - Answer:
"number" - Is array an object?
- Yes,
typeof [] → object - Difference between
typeofandinstanceof? typeof→ gives typeinstanceof→ checks class/constructor
Final Understanding
- Use
typeof→ for basic type checking - Use
in→ for checking object keys - Use
instanceof→ for checking object type/class