How to use the typeof operator In Javascript
If the type of the value is ‘object’ or ‘function’ then the value is not primitive otherwise the value is primitive. But the typeof operator shows the null to be an “object” but actually, the null is a Primitive.
Example: In this example, we are using the typeof operator
let isPrimitive = (val) => {
if(val === null){
console.log(true);
return;
}
if(typeof val == "object" || typeof val == "function"){
console.log(false)
}else{
console.log(true)
}
}
isPrimitive(null)
isPrimitive(12)
isPrimitive(Number(12))
isPrimitive("Hello world")
isPrimitive(new String("Hello world"))
isPrimitive(true)
isPrimitive([])
isPrimitive({})
Output
true true true true false true 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
Contact Us