0

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.

2
  • 3
    In your first one your overriding arguments, just don't put any parameters in it. eg.. function test () {.... Commented Aug 2, 2018 at 8:09
  • In the first case arguments itself is what you want. Commented Aug 2, 2018 at 8:12

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.