When I run this code on console its result is undefined
(function test (arguments) {
console.log(arguments[0]);
})(100);
But when I change arguments to a its result is 100
(function test (a) {
console.log(arguments[0]);
})(100);
Why? I googled and read MDN but can't figure out why first is undefined and second is 100.
3 Answers 3
arguments is a standard JavaScript variable which gets initalized in function's scope when you call it. It holds the arguments of the function call.
In the first snippet, you're overriding that behaviour by having your own arguments variable (which isn't an array). You're trying to get [0] out of it, which is undefined.
Second snippet works perfectly fine, because JS is able to get arguments variable normally.
Comments
because the arguments is self populated, in the first case the arguments you are trying to read as an array element an you are passing the number value (not an array),
In second, when you pass the value, you can access all the arguments via arguments array that is self populated and you can access based on index of arguments
Comments
As arguments is a reserve object or you can say is a local variable available within all (non-arrow) functions. So when you define a function with the same keyword it set the local variable to undefined.
And for other identifiers its not conflict with the arguments keyword.
That's why its showing undefined for 1st case and the value for second case.
function test () {....argumentsitself is what you want.