Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arguments and reference

Tags:

javascript

Consider this JavaScript function:

var f = function (a) {
  console.log(a+" "+arguments[0]);
  a = 3;
  console.log(a+" "+arguments[0]);
}

I would expect that a and arguments[0] reference the same value only up to the second statement of the function. Instead they appear to always refer the same value: f(2) causes

2 2
3 3

and f({foo: 'bar'}) causes:

[object Object] [object Object]
3 3

Are argument identifiers and the arguments identifier linked in a special way?

like image 693
Eric Avatar asked Mar 02 '15 16:03

Eric


People also ask

What is reference in argument?

A reference parameter is declared by preceding the parameter name in the function's declaration with an &. Operations performed on a reference parameter affect the argument used to call the function, not the reference parameter itself. Example. // Using reference parameter.

What is passing arguments by reference?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.

How are arguments passed by value and reference?

When you pass an argument by reference, you pass a pointer to the value in memory. The function operates on the argument. When a function changes the value of an argument passed by reference, the original value changes. When you pass an argument by value, you pass a copy of the value in memory.

What does arguments mean in coding?

Argument definition. An argument is a way for you to provide more information to a function. The function can then use that information as it runs, like a variable. Said differently, when you create a function, you can pass in data in the form of an argument, also called a parameter.


1 Answers

Are argument identifiers and the arguments identifier linked in a special way?

Yes (but only in non-strict mode).

From the specification (ES6, ES5):

For non-strict mode functions the integer indexed data properties of an arguments object whose numeric name values are less than the number of formal parameters of the corresponding function object initially share their values with the corresponding argument bindings in the function’s execution context. This means that changing the property changes the corresponding value of the argument binding and vice-versa. This correspondence is broken if such a property is deleted and then redefined or if the property is changed into an accessor property. For strict mode functions, the values of the arguments object’s properties are simply a copy of the arguments passed to the function and there is no dynamic linkage between the property values and the formal parameter values.

like image 59
Felix Kling Avatar answered Oct 06 '22 22:10

Felix Kling