Aaron
Aaron

Reputation: 3255

Parsing a variable datatype to a function which contains a conditional check on the datatype in JavaScript

To pass a datatype that varies (from an array to an integer) to the same function, and then check against the datatype before changing its value, looking at the below method using instanceof Array is there a better/more efficient way?

function foo(x) { 
  if (x instanceof Array) {
    for(i=0;i<x.length;i++){    
      x[i].bar = '1';
      x[i].baz = '2';       
    }   
  }
  else{
    x.bar = '1';
    x.baz = '2';    
  }
}

Thanks :)

Upvotes: 4

Views: 99

Answers (2)

basilikum
basilikum

Reputation: 10528

A more efficient way could also be to split up your function (if that is possible for you):

function fooArray(x) { 
    for(i = 0; i < x.length; i++){    
        foo(x[i]);   
    }   
}

function foo(x) {
    x.bar = '1';
    x.baz = '2'; 
}

This would also apply the DRY principle ("don't repeat yourself") because you don't need to code the same logic (i.e. x.bar = '1';) twice.

Upvotes: 1

Nagarjun
Nagarjun

Reputation: 2466

An alternative (using ECMAScript standard)

if( Object.prototype.toString.call( x ) === '[object Array]' ) {

    for(i=0;i<x.length;i++) {  

      x[i].bar = '1';
      x[i].baz = '2';       
    }  
}

See ECMAScript

Or if you always want it as an array, but this is not recommended

x = [].concat( x );

Upvotes: 2

Related Questions