Reputation: 69
Why does this function output 10?
function b (x, y, a) {
arguments[2] = 10;
console.log(a);
}
b(1, 2, 3);
Upvotes: 3
Views: 141
Reputation: 1046
The arguments object is a local variable available within all functions; arguments as a property of Function can no longer be used
use this reference for further
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments
Upvotes: 2
Reputation: 47280
javascript arrays are zero indexed and arguments refers to parameters passed into function as arguments :
arguments[2] === a === 10
and
1 === x === arguments[0];
2 === y == arguments[1];
(and triple equality operator is not a mistake)
Upvotes: 9
Reputation: 45083
This function takes three inputs, discards the first two and displays the last in a modal popup, but not before assigning value 10
to index 2
of arguments
- effectively setting the input a
to 10
from 3
- it then exits scope without returning anything at all.
Upvotes: 1
Reputation: 53198
Because you're setting the third argument to 10. From MDN:
You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0. For example, if a function is passed three arguments, you can refer to the argument as follows:
arguments[0] arguments[1] arguments[2]
Upvotes: 4