Where is arguments property defined? - javascript

Consider the following code
function add(x, y) {
alert(arguments.length);
var total = x + y;
return total;
}
add(); // NaN alerts 0
add(2,3); // 5 alerts 2
add(3,3,5); //6 alerts 3
Where is arguments defined? How come it is available inside my add function?

It is automatically created for all functions.
See https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments

A detailed explanation about when and how the arguments object is created:
From the ECMAScript specification:
10.1.8 Arguments Object
When control enters an execution context for function code, an arguments object is created and
initialised as follows:
The value of the internal [[Prototype]] property of the arguments object is the original Object prototype object, the one that is the initial value of Object.prototype (see 15.2.3.1).
A property is created with name callee and property attributes { DontEnum }. The initial value of this property is the Function object being executed. This allows anonymous functions to be recursive.
A property is created with name length and property attributes { DontEnum }. The initial value of this property is the number of actual parameter values supplied by the caller.
For each non-negative integer, arg, less than the value of the length property, a property is created with name ToString(arg) and property attributes { DontEnum }. The initial value of this property is the value of the corresponding actual parameter supplied by the caller. The first actual parameter value corresponds to arg = 0, the second to arg = 1, and so on. In the case when arg is less than the number of formal parameters for the Function object, this property shares its value with the corresponding property of the activation object. This means that changing this property changes the corresponding property of the activation object and vice versa.

That is just a standard feature of Javascript. Whenever any function is called, there is an arguments array automatically added to the local scope. This allows a function to receive a variable or unknown amount of parameters from the caller, and dynamically use these as necessary.
Commonly this is used when one function is placed as a wrapper around another where the exact parameters are unknown and arbitrary to the wrapper, who simply performs an action and then passes the provided arguments directly into the wrapped function.

arguments is a property of function objects. See Using the arguments object or Property: Function: arguments for more information.
It's worth noting that arguments is not a "real" array, the documentation calls it an "array-like object" - more in Turning JavaScript's arguments object into an array.

Related

Reflect.set not working as intended

It seems unlikely that I found some kind of glaring cross-browser bug. But according to the documentations Reflect.set is supposed to use the 4th parameter as the thisArg (for example if the set variable is a setter). The first argument is the object the value is to be set on, yet whenever I supply any object as the 4th argument, the value gets set on that instead of the target object.
var target = new Object;
var thisArg = new Object;
Reflect.set(target, 'variable', 52, thisArg);
target.variable == undefined
thisArg.variable == 52
Any explanation?
The first argument is the object the value is to be set on
Not exactly. The first argument is the object whose setters are invoked (including those on the object's prototype chain).
whenever I supply any object as the 4th argument, the value gets set on that instead of the target object.
Yes. Because the property always gets set on the receiver. It's just that the argument is optional because it's usually the same as the target, and therefore defaults to the first argument when not supplied.

Changing array member within local scope changes member in global scope

Why does JavaScript treat the scope of an array differently than it does the scope of other variables? Typically, if one passes a variable in a global scope into a function as a parameter, it is then local and changing it within the function does not change the value of the global variable. For example:
var globalInt = 1;
function test1(x){
x = x + 1
}
test1(globalInt);
console.log(globalInt); //globalInt is still 1
However, it appears the same does not apply when passing an array of values.
var globalArray = ["TEST"];
function test(x){
x[0] = x[0].toLowerCase()
}
test(globalArray);
//globalArray is now ["test"] instead of ["TEST"]
console.log(globalArray[0]);
This happens for me when I test in Chrome, but I have not tested it in other browsers so far. Why does this happen and does it happen in other browsers?
This is simply because an array (which is an Object) are passed by reference while primitives are not. Note that technically it is passed by value but in this case that value is a reference, thanks Esteban
A object is automatically passed by reference, without the need to specifically state it
If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as a parameter and the function changes the object's properties, that change is visible outside the function, as shown in the following example:
MDN Link
Yes... JavaScript objects and arrays (which are objects) are passed by reference. But you should remember to read the method signature explicitly because some array methods don't alter the original array but return a new one. Read the MDN documentation carefully about the method in question. Array.prototype.map() would actually leave the original array intact and return a brand new array which you'd need to set to assign to a variable.

Can someone explain this function in JavaScript [duplicate]

This question already has answers here:
Applying a Function to Null in Javascript
(5 answers)
Closed 7 years ago.
I am learning about call and apply in javaScript from a online TUT. This function allows more arguments to be passed, rather than having a fixed amount.
var calculate = function(){
var fn = Array.prototype.pop.apply(arguments);
return fn.apply(null, arguments);
};
What I am having difficulty wrapping my head around is this statement.
var fn = Array.prototype.pop.apply(arguments);
The presenter of the of the TUT, explained it as the following:
We are binding the apply method onto the arguments object. This is going to give us the Function Object and assign it to the fn variable. It will also remove the Function Object from the argumentsObject. Because the Array's pop method takes the final element in the array, it removes it from the Array and then assigns to what ever called the method. In this case the fn variable.
What confused me was the following:
We are binding the apply method onto the arguments object. This is
going to give us the Function Object
It will also remove the Function Object from the arguments
Object.
And when we write in the return statement:
return fn.apply(null, arguments);
Why are we including null?
Array.prototype.pop.apply(arguments);
When you have a function, there's automatically an arguments objects, which is an Array-like object of arguments. If you call this fake function:
someFunction('hello', 'world');
and someFunction looks like this:
function someFunction() {
console.log(arguments);
}
The console.log will output ['hello', 'world']. However, don't be confused... That is not an Array object! It is an "array-like" object. Therefore, you can't say arguments.pop()... because arguments doesn't have that method (it belongs to Array.prototype). However, normal Array objects do have access to Array.prototype (e.g. [1,2,3].pop() // => [1,2]).
When you say .apply(), the first argument is the context... It sets the this. So really, Array.prototype.pop.apply(arguments) is a clever way of mimicking arguments.pop(). But you can't do arguments.pop(), because it doesn't have a pop method.
In return fn.apply(null, arguments);, null is the first arguments because we don't need to set a new context for this example. arguments is the second arguments because it's being passed in to use with fn.
.apply() returns a function object, so it returns something like this:
function() { ... }
We can then later invoke that function.
By the way, .pop() mutates the original object (in this case, the array-like object arguments). So you're passing in arguments to fn, but it's missing the last item that was in it previously.
According to MDN:
Syntax
fun.apply(thisArg, [argsArray])
Parameters
thisArg:
The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.
argsArray:
An array-like object, specifying the arguments with which fun should be called, or null or undefined if no arguments should be provided to the function. Starting with ECMAScript 5 these arguments can be a generic array-like object instead of an array. See below for browser compatibility information.
The last argument passed to calculate is assumed to be a function. It is popped from the arguments list. (Using apply because arguments is not a real array.)
This popped function (fn) is called with the rest of the arguments list. (All other arguments passed to calculate). The arguments list no longer contains fn because pop() modifies the original object.
NULL is used because fn is called without a value for this. (See MDN)
If you call calculate for instance like
calculate(2, 3, function(a, b){ return a + b });
it will return 5.

Arguments and reference

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?
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.

javascript object properties as parameters

If in javascript object properties are passed by reference why this doesnt work:
var myObj={a:1}
function myFun(x){
x=2;
}
myFun(myObj.a);
// value myObj.a is still 1
but on the other hand if you do this:
var myObj={a:1}
function myFun(x){
x.a=2;
}
myFun(myObj);
// this works myObj.a is 2
Primitive values are passed by value. Objects are passed by reference.
Object properties are passed by based on their data type.
Here you are passing an integer - x represents the value 1. Assigning x the value 2 does not reference the original object.
Let's say the property you pass in is an array. And the 2nd function I call receives an array and you make changes to that array. Then the changes will persist to the object because the object's property contains a reference to the array you modified. You didn't technically modify the object at all... you just modified the array which is referenced in the object. When you pass an object property to a function, it's not aware that it belongs to an object at all.
See example, similar to yours:
var myObj={a:[1]}
function fn1(x){
x=2; //Overwrites x in this scope to the new primitive 2.
//This isn't reflected in myObj because x is not a
//reference to myObj.a it is a reference to the array
//that myObj.a contains (the [1]).
}
function fn2(x){
x.push(2);
}
fn1(myObj.a); //myObj.a is [1]
fn2(myObj.a); //myObj.a is [1,2]
your first example doesn't work, because object properties are not passed by reference (unless the property itself also is an object).
objects, as you noticed, are passed by reference - thats the reason your second example works.
When you pass a base data type, it is passed by value. That is for integers, you pass the parameter by value so a copy of it is made in the local scope. Objects however are passed by reference so the function has access to the variable. You could pass it by reference, but its easier to do
Obj.a=fun(Obj.a);

Categories