Hemadri Dasari
Hemadri Dasari

Reputation: 33984

The importance of arguments object in JavaScript

I am very new to arguments object concept in JavaScript and trying to understand the concept from this tutorial.

The below example from the doc explains as follows.

 function func1(a, b, c) {
      console.log(arguments[0]);
      // expected output: 1

      console.logr(arguments[1]);
      // expected output: 2

     console.log(arguments[2]);
     // expected output: 3
 }

 func1(1, 2, 3);

But I am unable to understand the importance of this concept and in which scenario we mostly use such concept?

Excuse me for question format issues as I am typing in mobile.

Upvotes: 0

Views: 319

Answers (2)

Martin Eden
Martin Eden

Reputation: 11

function summIt(){
    let result = 0;
    let args = [...arguments];
    
    args.forEach(el => result += el);
      
    return result;
}
    
console.log(summIt(4,7,4,8,9,3,3)); //38

OR

const summ = (...args) => {
    let result = 0;
    
    Array.from(args).forEach(el => result += el);
      
    return result;
}
    
console.log(summ(4,7,4,8,9,3,3)); //38

Upvotes: 0

Axnyff
Axnyff

Reputation: 9944

The arguments object is useful in cases you have possibly a variable number of arguments:

function sumAll() {
  var res = 0;
  for (var i = 0; i < arguments.length; i++) {
    res += arguments[i];
  }
  return res;
}

console.log(sumAll(3)); // 3
console.log(sumAll(3, 4, 5)); // 12

However, since ES6, a version of javascript standardized in 2015 ( also called ES2015), you can use the rest parameter syntax to simplify this operation:

function sumAll(...args) {
    var res = 0;
    for (var i = 0; i < args.length; i++) {
        res += args[i];
    }
    return res;
}

console.log(sumAll(3)); // 3
console.log(sumAll(3, 4, 5)); // 12

The arguments object is therefore no longer necessary.

Upvotes: 4

Related Questions