Open In App

How to check if the value is primitive or not in JavaScript ?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Using the typeof operator

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

Javascript




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

Using the Object()

In this we check if the value is equal to Object(value). If the value is equal then the value is primitive otherwise not primitive.

Syntax

Value !== Object(inputValue);

Example: In this example, we are using Object().

Javascript




let isPrimitive = (val) => {
   
  if(val === Object(val)){
    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


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads