Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do arrow functions not have the arguments array? [duplicate]

function foo(x) {    console.log(arguments) } //foo(1) prints [1] 

but

var bar = x => console.log(arguments)  

gives the following error when invoked in the same way:

Uncaught ReferenceError: arguments is not defined 
like image 888
Conqueror Avatar asked Jan 19 '17 00:01

Conqueror


People also ask

Why arrow functions do not have arguments?

Arrow functions do not have an arguments binding. However, they have access to the arguments object of the closest non-arrow parent function. Named and rest parameters are heavily relied upon to capture the arguments passed to arrow functions.

Does arrow function have its own arguments object?

Arrow functions don't have their own arguments object. Arrow functions do not expose an arguments object to their code: arguments. length , arguments[0] , arguments[1] , and so forth do not refer to the arguments provided to the arrow function when called.

What are the disadvantages of arrow function?

An Arrow function should not be used as methods. An arrow function can not be used as constructors. An arrow function can not use yield within its body. Arrow function cannot be suitable for call apply and bind methods.

Do arrow functions define arguments?

The arrow function, on the opposite, doesn't define arguments (but you can easily access the arrow function arguments using a rest parameter ... args ). If the arrow function has one expression, then the expression is returned implicitly, even without using the return keyword.


1 Answers

Arrow functions don't have this since the arguments array-like object was a workaround to begin with, which ES6 has solved with a rest parameter:

var bar = (...arguments) => console.log(arguments); 

arguments is by no means reserved here but just chosen. You can call it whatever you'd like and it can be combined with normal parameters:

var test = (one, two, ...rest) => [one, two, rest]; 

You can even go the other way, illustrated by this fancy apply:

var fapply = (fun, args) => fun(...args); 
like image 188
Sylwester Avatar answered Sep 30 '22 08:09

Sylwester