Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 912
dimko1 Avatar asked May 26 '15 12:05

dimko1


1 Answers

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 ;)

like image 167
sp00m Avatar answered Sep 27 '22 18:09

sp00m