0

I am not at all able to decode the output for this js code snippet. The output actually shows 3 . I expected output to be 4. Can someone please explain what is going on here, or am I missing some crude concept of javascript.

var length = 4;
function callback() {
    
  console.log(this.length);
}
const object = {
  length: 5,
  method() {
    
    arguments[0]();
  }
};
object.method(callback, 1, 2);
Sarwan
  • 595
  • 3
  • 8
  • 21
  • this.length is inside the function block so it is returning Function.length. The length property indicates the number of parameters expected by the function. So you are seeing 3 in the console because there are 3 parameters passed in your object.method. Change the number of parameters and you will see a different value output in the console. More info here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length – nontechguy Nov 21 '21 at 06:23
  • @nontechguy: That’s not correct (there are no functions with 3 parameters in the question); it’s returning `arguments.length` because it was called as a method (`[0]`) of `arguments`. – Ry- Nov 21 '21 at 07:26
  • Thanks @Ry, I am always happy to learn from others. I understood as follows - object.method(callback, 1, 2); // 3 parameters. Changing the number of parameters passed in the method changes the output of console.log(this.length) so object.method(callback, 2) outputs the value 2 in the console. – nontechguy Nov 21 '21 at 08:42
  • @nontechguy: First, it’s a bit pedantic, but important in order to be specific here: the “arguments” are part of a function call (`alert(1)` – the argument list is `(1)`), and the “parameters” belong to the function itself (`function foo(bar) {}` – the parameter list is `(bar)`). Anyway, you mentioned `Function.length` and linked to the `length` property of functions, but what’s being read here is `arguments.length` (`this` inside `callback` is equal to `arguments` inside `method`), and `arguments` is not a function. – Ry- Nov 21 '21 at 09:12
  • @Ry what is meant by called as a method of arguments and how is it different from normal function calls. Any MDN specs to refer here will be really helpful to get more insights into this. – Sarwan Nov 21 '21 at 15:25

0 Answers0