Skip to content
Advertisement

Javascript arguments shifting

Let’s assume that we have the following function:

var a = function(data, type){
  var shift = [].shift;
  shift.call(arguments);
  shift.call(arguments);
  shift.call(arguments);
  shift.call(arguments);
  console.log(data);
}

a(1,'test', 2, 3);

I understand that data and type are just references to specific values in arguments. But why in the end, data is equal to 3?

Advertisement

Answer

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#Making_eval_and_arguments_simpler:

Strict mode makes arguments less bizarrely magical.

In normal code within a function whose first argument is arg, setting arg also sets arguments[0], and vice versa (unless no arguments were provided or arguments[0] is deleted).

arguments objects for strict mode functions store the original arguments when the function was invoked. arguments[i] does not track the value of the corresponding named argument, nor does a named argument track the value in the corresponding arguments[i].

You actually met the “unless arguments[i] is deleted” case 😉

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement