Arguments vs Arrays

I saw a job posting that illustrated the JavaScript/ECMAScript knowledge-level the candidate needed with:

can you figure out whether you’re working with an array or arguments list without the use of 3rd party code?

I was intrigued, because I didn’t know the answer.

Two ways (of many, I’m sure) to determine the type of JavaScript Object you’re working with is by using instaceof or Object.prototype.toString

instaceof

Instaceof will give you a boolean response. It’s useful to determine if you’re working with a specific kind of object.

1
2
3
4
5
6
7
function bob(one, two, three) {
  var x = arguments;
  var y = [];
  
  console.log ( x instanceof Array ); //false
  console.log ( y instanceof Array ); //true
};

Instanceof evaluates to true if the object inherits from the class’s prototype:

1
2
var p = new Person("Richard");
p instanceof Person //true

This evaluates to true since p inherits from Person.prototype. It’s worth noting that using the new keyword is imperative.

Arguments is not a valid instanceof object, so we can only use this to tell if we’re dealing with an Array or something else.

Object.prototype.toString

Calling this returns the type of object

1
2
3
4
5
6
7
function bob(one, two, three) {
  var x = arguments;
  var y = [];
  
  console.log( Object.prototype.toString.call( x ) ); //[object Arguments]
  console.log( Object.prototype.toString.call( y ) ); //[object Array]
};

You could then use indexOf or search to check for ‘Arguments’ or ‘Array’.

Without a doubt, there are other ways to do this in JavaScript. That’s what makes it fun—you’re never done learning.