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);
5
  • 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 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Nov 21, 2021 at 6: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. Commented Nov 21, 2021 at 7: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. Commented Nov 21, 2021 at 8: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. Commented Nov 21, 2021 at 9: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. Commented Nov 21, 2021 at 15:25

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.