How to use the instanceof operator In Javascript
The instanceof operator checks whether an object belongs to a specific class or not. While it’s typically used to check if an object is an instance of a particular constructor function, it can also be used to differentiate between primitive and non-primitive values.
Example:
function isPrimitive(value) {
return (
value instanceof Number ||
value instanceof String ||
value instanceof Boolean ||
value instanceof Symbol ||
value instanceof BigInt
);
}
console.log(isPrimitive(null));
console.log(isPrimitive(12));
console.log(isPrimitive(Number(12)));
console.log(isPrimitive("Hello world"));
console.log(isPrimitive(new String("Hello world")));
console.log(isPrimitive(true));
console.log(isPrimitive([]));
console.log(isPrimitive({}));
Output
false false false false true false false false
How to check if the value is primitive or not in JavaScript ?
To check if the value is primitive we have to compare the value data type. As Object is the non-primitive data type in JavaScript we can compare the value type to object and get the required results.
Primitive data types are basic building blocks like numbers and characters, while non-primitive data types, such as arrays and objects, are more complex and can store multiple values or structures.
- Primitive data types − String, number, undefined, boolean, null, symbols, bigint.
- Non-primitive data types − Object
When we access a primitive value, we manipulate the actual value stored in that variable. Thus, variables that are primitive are accessed by value. When we assign a variable that stores a primitive value to another, the value stored in the variable is created and copied into the new variable.
To check a value whether it is primitive or not we use the following approaches:
Table of Content
- Using the typeof operator
- Using the Object()
- Using the instanceof operator