Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

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

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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
Last Updated : 10 Jan, 2023
Like Article
Save Article
Similar Reads
Related Tutorials