DEV Community

Cover image for What is the arguments object in a regular function, and why is it unavailable in arrow functions?
Karthick (k)
Karthick (k)

Posted on

What is the arguments object in a regular function, and why is it unavailable in arrow functions?

The arguments object in JavaScript allows you to access all the arguments passed to a function as an array-like object. This feature is particularly useful when dealing with older or more complex functions where you might not know how many arguments will be passed at runtime. However, this object is unavailable in arrow functions due to their lexical scoping nature.

Let's break down the key points and discuss why the arguments object works differently between regular functions and arrow functions.

Code

// Example of using `arguments` in a regular function
function sum() {
    let total = 0;
    for (let i = 0; i < arguments.length; i++) {
        total += arguments[i];
    }
    return total;
}
console.log(sum(1, 2, 3)); // Output: 6

// Attempting to use `arguments` in an arrow function will result in an error
const sumArrow = (...args) => {
    let total = 0;
    for (let i = 0; i < arguments.length; i++) { // This line causes an error
        total += arguments[i];
    }
    return total;
};
Enter fullscreen mode Exit fullscreen mode

Flowchart

Top comments (0)