Junior — Middle
Can you explain what the arguments object in JavaScript is?
sobes.tech AI
Answer from AI
In JavaScript, the arguments object is a local variable within a function that contains all the arguments passed to it in the form of an array-like object.
Features of arguments:
- Allows access to function arguments without explicitly declaring parameters.
- Is not a true array, but has a length and indices.
- Useful for functions with a variable number of arguments.
Example of usage:
function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
console.log(sum(1, 2, 3)); // 6
In modern JavaScript standards, it is preferable to use the rest operator (...args), which creates a true array of arguments.