How to use the Object() In Javascript
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().
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
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