-2

I was reading about arrow function in js. There I found one question.

var arguments = [1, 2, 3];
var arr = () => arguments[2];
console.log(arr());

function foo(n) {
  var f = () => arguments[0] + n;
  return f();
}
console.log(foo(3));

It's output is showing 6. Can anyone explain why it is so?

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
  • 1
    You do `arguments[0]` which is 3 and then you add `n` which is also 3. That does 6 – polypode Nov 05 '21 at 06:24
  • @polypode How arguments[0] = 3 ? – Deepak soni Nov 05 '21 at 06:25
  • `arguments` within your `foo` function is not the `var arguments` defined previously. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments – Phil Nov 05 '21 at 06:28
  • 2
    What do you expect instead? `arguments` and arrow functions are documented on MDN ([`=>`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Arrow_functions), [`arguments`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/arguments)) and in the [specification](//tc39.es/ecma262/#sec-function-calls). – Sebastian Simon Nov 05 '21 at 06:28
  • Strongly related: [No binding of arguments in JavaScript](/q/46032751/4642212). I mean… this example is taken from MDN; you were reading MDN. MDN links to its article about `arguments` and it’s explained very clearly there. I really don’t see what else you were expecting this code to do or how you could miss what `arguments` is. – Sebastian Simon Nov 05 '21 at 06:35

1 Answers1

2

arguments is the object for getting the arguments of the function called. Therefore arguments[0] is the argument n.

You need to change the name of the array such as arr = [1,2,3] and use it in the foo() function f = () => arr[0] + n;

var arr = [1, 2, 3];
var bar = () => arr[2];
console.log(bar());

function foo(n) {
  var f = () => arr[0] + n;
  return f();
}
console.log(foo(3));
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
  • Neither the `arr` function nor the external `argument` has anything to do with the original question and the result the they got which was 6 – smac89 Nov 05 '21 at 06:27
  • 1
    Okay so this argument inside foo() is a new arguments .It has nothing to do with above argument array. – Deepak soni Nov 05 '21 at 06:28
  • @smac89 what about console.log(bar()); line? It is also printing – Deepak soni Nov 05 '21 at 06:30
  • @Deepaksoni the only function call in your question that prints 6 is the `foo(3)` – smac89 Nov 05 '21 at 06:31
  • 1
    Slight correction... `arguments` is the object for getting the arguments of the _regular_ function called. Arrow functions do not have access to that `arguments` but they will have access to anything in scope – Phil Nov 05 '21 at 06:32
  • In addition to @Phil 's comment, you can have a look at this thread: https://stackoverflow.com/questions/30935336/official-information-on-arguments-in-es6-arrow-functions – Harun Yilmaz Nov 05 '21 at 06:33