-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?

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
Kevin
  • 795
  • 2
  • 9
  • 21
  • we can use it for unknown parameter so... – Bhojendra Rauniyar Jan 21 '15 at 05: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: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments – Brennan Jan 21 '15 at 06:01

1 Answers1

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);
}
JLRishe
  • 99,490
  • 19
  • 131
  • 169