66

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.

5
  • A specific type of primitive, or just any old not-an-object primitive? Commented Jul 21, 2015 at 11:39
  • Have you tried using typeof myVar !== 'object' && typeof myVar !== 'string'... ? Commented Jul 21, 2015 at 11:40
  • Relevant documentation: typeof operator Commented Jul 21, 2015 at 11:40
  • 1
    @AnthonyGrist - any old not-an-object primitive. Commented Jul 21, 2015 at 11:41
  • This is a duplicate of many questions. Commented Jul 21, 2015 at 11:42

2 Answers 2

88

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/

Sign up to request clarification or add additional context in comments.

10 Comments

Am I right when I feel that it has a performance overhead as the price of code simplicity?
@Zoltán Tamási, yeah you are right, about 7 times slower than instanceof check
Not worth an edit, but you don't need the ; after a function declaration (as opposed to a function expression like var isPrimitive = function(test) {...};).
Object(undefined) !== undefined is true
@Artemiy StagnantIce Alexeew Didn't you expect so? Undefined is a primitive type.
|
21

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

1 Comment

Am I right when I feel that it has a performance overhead as the price of code simplicity?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.