Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking the type of a variable

Tags:

javascript

What's the best way to find out whether a variable is a string or not (and, likewise, a number, a boolean, etc.)?

Usually you will find:

function isString(value) {
    return typeof value === 'string';
}

But people forget that one can also create string objects directly using var foo = new String("bar"); - whether that is a good idea or not is an entirely different matter.

So what's the way to go here? I can think of - and have seen - various approaches (somewhat simplified):

// option 1
function isString(value) {
    return (typeof value === 'string') ||
           /^function String\(\)/.test(value.constructor + '');
}

or

// option 2
function isString(value) {
    return (typeof value === 'string') ||
           (value.constructor === String);
}

or

// option 3
function isString(value) {
    return (typeof value === 'string') ||
           value instanceof String;
}

Is there a "best" way to go about this? Or are they all equivalent?

like image 286
n3rd Avatar asked Jan 28 '11 13:01

n3rd


1 Answers

Among the three existing options, the first feels rather hacky to me because it uses a regular expression to test the string representation of value.constructor. It works, but it still feels hacky (maybe it's just me).

The second option would only work for string literals, strings created from concatenating existing objects and objects made with the new String() constructor, whereas the third option should work with objects made with the new String() constructor or any other object that inherits from String() (I'm not sure about JavaScript inheritance; can someone confirm this?).

The constructor property exists also for primitives/literals, not just wrapper objects created using new. This makes the typeof check in the second option quite redundant:

function isString(value) {
    return value.constructor === String;
}

alert(isString("test1"));             // true
alert(isString(new String("test2"))); // true

However, unlike the third option it may not work with objects with constructors other than String() that inherit from String().

My answer uses strings as an example to reflect the question but the same idea applies to Number, Boolean, Function, Object, Array and other types.

like image 86
BoltClock Avatar answered Sep 24 '22 08:09

BoltClock