Phillip Senn
Phillip Senn

Reputation: 47595

Is there a shortcut syntax for checking types of variables?

In JavaScript, how do I say:

if (typeof obj === 'number' 
    || typeof obj === 'boolean' 
    ||  typeof obj === 'undefined' 
    || typeof obj === 'string') {

In other words, is there some kind of:

if (typeof obj in('number','boolean','undefined','string')) {

Upvotes: 1

Views: 377

Answers (5)

RobG
RobG

Reputation: 147373

More grist for the mill:

if ( ('object function string undefined').indexOf(typeof x) > -1) {
  // x is an object, function, string or undefined
}

or

if ( (typeof x).match(/object|function|string|undefined/)) {
  // x is an object, function, string or undefined
}

How many ways do you want this cat skinned?

Upvotes: 2

kba
kba

Reputation: 19466

Yes there is. typeof(obj) just returns a string, so you can simply do as you would when checking if a string is in any set of strings:

if (typeof(obj) in {'number':'', 'boolean':'', 'undefined':'', 'string':''})
{
  ...
}

Or you could make it even shorter. Since the only "types" that typeof may return are number, string, boolean object, function and undefined, in this particular case, you could just make an exclusion instead.

if (!(typeof(obj) in {'function':'', 'object':''}))
{
  ...
}

Upvotes: 3

Dmytrii Nagirniak
Dmytrii Nagirniak

Reputation: 24088

I like to use functional programming for similar situations. So you can use underscore.js to make it more readable:

_.any(['number','boolean','undefined','string'], function(t) {
  return typeof(obj) === t; 
});

Upvotes: 1

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

You could approximate it with something like

var acceptableTypes = {'boolean':true,'string':true,'undefined':true,'number':true};

if ( acceptableTypes[typeof obj] ){
  // whatever
}

or the more verbose

if ( typeof obj in acceptableTypes){
  // whatever
}

Upvotes: 4

Guffa
Guffa

Reputation: 700302

You can use a switch:

switch (typeof obj) {
  case 'number':
  case 'boolean':
  case 'undefined':
  case 'string':
    // You get here for any of the four types
    break;
}

In Javascript 1.6:

if (['number','boolean','undefined','string'].indexOf(typeof obj) !== -1) {
  // You get here for any of the four types
}

Upvotes: 6

Related Questions