šŸ“™ Understanding Neuronal Networks presale is now open - 20% off discount!

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.

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!


Leave a Reply

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