Is it possible to test a variable to see if it is a primitive?
I have seen lots of questions about testing an variable to see if it is an object, but not testing for a primitive.
This question is academic, I don't actually need to perform this test from my own code. I'm just trying to get a deeper understanding of JavaScript.
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.
Primitives are passed by value, i.e. a copy of the primitive itself is passed. Whereas for objects, the copy of the reference is passed, not the object itself. Primitives are independent data types, i.e. there does not exist a hierarchy/super class for them. Whereas every Object is descendent of class "Object".
In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties.
To test for any primitive:
function isPrimitive(test) { return test !== Object(test); }
Example:
isPrimitive(100); // true isPrimitive(new Number(100)); // false
http://jsfiddle.net/kieranpotts/dy791s96/
Object
accepts an argument and returns if it is an object, or returns an object otherwise.
Then, you can use a strict equality comparison, which compares types and values.
If value
was an object, Object(value)
will be the same object, so value === Object(value)
. If value wasn't an object, value !== Object(value)
because they will have different types.
So you can use
Object(value) !== value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With