Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Last Updated : 31 Mar, 2021
View Discussion
Improve Article
Save Article

In this article, we will know how to check if a value of primitive or not.

JavaScript provides six types of primitive values that include Number, String, Boolean, Undefined, Symbol, and BigInt. The size of primitive values is fixed, therefore JavaScript stores the primitive value in the call stack (Execution context).

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:

Approach 1: In this approach, we check the type of the value 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:

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

Approach 2: In this approach, we pass the value inside Object() and check if the value is equal to Object(value). If the value is equal then the value is primitive otherwise not primitive.

Example:

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!