Arrow functions don’t have access to the arguments object as regular functions

While with a normal function you can use the arguments implicit object to see the given params:

function myFunction() {
    console.log(arguments);
}
myFunction('a', 'b');
// logs { 0: 'a', 1: 'b', length: 2 }

In an arrow function this will end up with an unexpected result:

function myFunction() {
    const arrowF = () => console.log(arguments);
    arrowF('c', 'd');
}

myRegularFunction('a', 'b'); 
// will log { 0: 'a', 1: 'b', length: 2 } 
// insead of the expected { 0: 'c', 1: 'd', length: 2 }

This happens because of the fact that that arrow functions don't have an arguments object. They also don't have their own this context and therefore the arguments is the one from the myRegularFunction context.

However, we can use a rest parameter to spread the arguments in an arrow function:

function myRegularFunction() {
    const arrowF = (...args) => console.log(args); 
    arrowF('c', 'd');
}
myRegularFunction('a', 'b'); 
// logs ['c', 'd']

And we can even make some cool stuff like combining regular parameters with a rest parameter:

function multiplyTheSum(multiplier, ...numbers) {
    console.log(multiplier); // 2
    console.log(numbers);    // [10, 20, 30]
    const sum = numbers.reduce((s, n) => s + n);
    return multiplier * sum;
}
multiplyTheSum(2, 10, 20, 30); // => 120

Btw, if you are interested you can read more also about the function declarations vs the function expressions and when it's best to use a regular function instead of an arrow function.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X