Thursday, February 05, 2015

Javascript "arguments" weirdness

I was using this JavaScript function that I wanted to accept an array of arguments or just a bunch of arguments that would be interpreted as an array. As you probably know, for each function in JS you get a variable called arguments which contains the arguments to the function. It is a pseudo array, not a real array, and has some extra properties. My code looked like this:
function x(arg) {
  if (!arg) {
    arg=[];
  } else if (!arg.length) {
    arg=[];
    for(var i=0; i<arguments.length; i++) arg.push(arguments[i]);
  }
  // do something with arg
}

The logic is simple, if there is no first parameter, arg becomes an empty array, else, if there is a first argument, but it doesn't have a length property (not an array) set arg to an array and push all arguments of the function as items of the array. But it doesn't work! The point is this: you set arg to an empty array and at that moment arguments[0] is no longer the original argument, but the empty array. Even worse, the code then adds the array as an item of itself, which makes the object be infinitely recursive.

Let's make this simpler:
function x(arg) {
  arg=[];
  console.log(arguments[0]);
}
After you execute x() with any arguments, the console will show an empty array, not the original argument. Weird, huh?

0 comments: