Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test if a variable is a primitive rather than an object? [duplicate]

Tags:

javascript

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.

like image 825
Chris Snow Avatar asked Jul 21 '15 11:07

Chris Snow


People also ask

How do you know if a value is primitive?

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.

How does a primitive type differ from an object?

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".

Is object a primitive data type?

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties.


2 Answers

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/

like image 158
kieranpotts Avatar answered Oct 05 '22 23:10

kieranpotts


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 
like image 21
Oriol Avatar answered Oct 05 '22 23:10

Oriol