-3

I noticed that in some functions the arguments object is used:

function fn(arg1, arg2)
{
    console.log(arguments[0])
}

fn(1, 2); // 1

Why it is useful?

2
  • we can use it for unknown parameter so... Commented Jan 21, 2015 at 5:59
  • The arguments object is kind of special, but it's most commonly used for a variable number of args. There are useful properties like caller and callee as well. More info: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jan 21, 2015 at 6:01

1 Answer 1

2

In your example, it's not useful and not a good idea. It can be useful when you want a function that can accept an indefinite number of arguments:

function sum() {
    var total = 0;
    for (var i = 0; i < arguments.length; i += 1) {
        total += arguments[i];
    }
    return total;
}

console.log(sum(5, 6, 7, 8));   // 26

Note that ES6 allows the use of rest parameters which would be more useful in most cases where arguments are used nowadays:

function sum(...values) {
    return values.reduce(function (prev, cur) {
        return prev + cur;
    }, 0);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.