Reputation: 19
I am Korean, so I hope you could understand it with my awkward English skills
I am studying arrow function expressions
and here is my question with source code
var arguments = [1, 2, 3];
var arr = () => arguments[0];
console.log(
arr()
)
function foo(n){
var f = () => arguments[0] + n
console.log(arguments[0]) //5
console.log("----arguments[0]")
return f();
}
console.log(
foo(5)
)
console.log("---------------------")
function fooo(n){
var f = (...arguments) => arguments[0] + n
console.log(...arguments) //5
console.log("----...arguments")
return f(2);
}
console.log(
fooo(5)
)
I don't get why the second function's console.log = 10 and third function's = 7 can anyone explain to me the order code process and why that output is? thank you.
Upvotes: 0
Views: 78
Reputation: 23778
In JS, every conventional function has a built-in object called arguments
. However, Arrow functions do not have this built-in object. So, if referred to arguments
from within an Arrow function, the reference automatically goes to any external variable declared by that name.
The result you see is due to this effect. In regular function calls. your reference to the arguments
global variable actually refers to their in-built arguments
object.
The following code demonstrates this effect.
let arguments = 'this is a string';
function argumentsTest() {
console.log(arguments);
}
let argumentsArrowTest = () => {
console.log(arguments);
}
argumentsTest(10); //{0: 10}
argumentsArrowTest(10); // this is a string
Upvotes: 2
Reputation: 370699
In an arrow function, arguments
, like this
, will refer to either
arguments
(though it's very unusual to call a variable arguments
due to name collision), orfunction
whichever is closer, lexically.
In foo
,
var f = () => arguments[0] + n
is an arrow function, so arguments
refers to an outer binding. The outer environment is
function foo(n){
var f = () => arguments[0] + n
so arguments
refers to the arguments provided to foo
. Here, it's similar to doing
function foo(n){
const theArguments = [n];
var f = () => theArguments[0] + n
And since the argument passed to foo
is 5, that plus n
(the same argument) is 10.
In the third function, the same logic applies. Inside an arrow function, arguments
refers to the closest identifier named arguments
, or the closest function. Here, it's the parameters:
var f = (...arguments) => arguments[0] + n
Since f
is called with a single argument, this simplifies to
var f = (arg) => arg + n
That argument is 2, and the n
is what's passed to fooo
, which is 5. Add them together, you get 7.
Upvotes: 0