[SOLVED] Is there a way to access the "arguments" object inside of a closure?

Issue

I have a closure, and I want to access the arguments to the closure from inside the closure. Is this possible?

function outerFunction (param1, param2) {
  // Returns [param1, param2, [param1, param2]]
  return function innerFunction () { return [param1, param2, arguments] }
}

// [1, 2, [1, 2]]
console.log(outerFunction(1, 2)(3, 4));

Solution

arguments is a special beast, and follows different rules in sloppy mode than in strict mode. It is array-like, but not a real array. But it is not necessary to use it. Just use rest parameter syntax:

function outerFunction (param1, param2) {
  return function innerFunction (...args) { 
    return [param1, param2, args];
  };
}

let result = outerFunction(1, 2)(3, 4);
console.log(result); // [1, 2, [3, 4]]

Answered By – trincot

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *