Home > Software design >  The answer should return 4. idk how arguments[0] is returning 3 as its value and foo(3) is returning
The answer should return 4. idk how arguments[0] is returning 3 as its value and foo(3) is returning

Time:12-06

var arguments = [1,2,3];
var arr=()=>arguments[0];

console.log(arr()); //returns 1

function foo(n){
    console.log(arguments[0]); //returns 3 should have returned 1 as arguments[0] is 1
    var f=()=>arguments[0] n;
    return f();
}

console.log(foo(3)); //returns 6

The above is a JavaScript code I have tried executing the code and the answer is correct I guess but I am unable to understand how arguments[0] is returning 3 instead of 1.

CodePudding user response:

In JavaScript, the arguments object is a local variable that is available inside every function. It is an array-like object that contains the arguments that were passed to the function. In your code, arguments[0] inside the foo function refers to the first argument passed to foo, which is 3.

var arr = (...args) => args[0];

console.log(arr(1, 2, 3)); // returns 1

function foo(n, ...args) {
  console.log(args[0]); // returns 1
  var f = (...innerArgs) => innerArgs[0]   n;
  return f(args[0]);
}

console.log(foo(3, 1, 2, 3)); // returns 4

In this updated code, I used the rest parameter syntax (...args) to capture the arguments passed to arr and foo as arrays. This allows us to access the first argument passed to these functions using args[0], rather than the arguments object. I also used the rest parameter syntax inside foo to capture the arguments passed to f as an array. This allows us to access the first argument passed to f using innerArgs[0], rather than the arguments object.

CodePudding user response:

What you are seeing is foo(3) arguments[0] is 3 and then you add n (3) to it and get 6. The global arguments[0] is equal to 1 so that is why you are seeing different results. It is due to variable scope and is working how it should.

  • Related