1

let temp = {
  a: 10,
  b: 20,
  sum() {
    return this.a + this.b;
  },
  multi: () => {
    return this.a * this.b;
  },
};

console.log(temp.sum())
console.log(temp.multi())

I am beginner is JavaScript. I want to ask why the output of the code is

30 and NaN
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0x192
  • 31
  • 2
  • 1
    You should read about [Arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), I am sure, your doubt will be clear – Arif Khan Oct 23 '21 at 04:25

3 Answers3

3

Syntax is wrong, use

multi: function() {
    return this.a * this.b;
}

in the object.

Edit

The reason the arrow function [=>()] gives an error is because it does not recognize this as the context of the object it is called on but, in this case, the global context. Hence this result.

var a=2, b=5;
let temp = {
  a: 10,
  b: 20,
  sum() {
    return this.a + this.b;
  },
  multi: () => {
    return this.a * this.b;
  },
};

console.log(temp.sum());
console.log(temp.multi());
Syn
  • 43
  • 5
1

The reason it is returning NaN when calling multi() is because of the peculiarity of the this keyword. The this in the multi function is not referring to the temp object as you might expect but instead referring to the global this. Run the following code to see the specific values being used in multi:

let temp = {
  a: 10,
  b: 20,
  sum() {
    console.log('running `sum`:', 'this === window?', this === window);
    console.log(this.a, this.b, this.a + this.b);
    return this.a + this.b;
  },
  multi: () => {
    console.log('running `multi`:', 'this === window?', this === window);
    console.log(this.a, this.b, this.a * this.b);
    return this.a * this.b;
  }
};

console.log(temp.sum());
console.log(temp.multi());

In order to resolve it in multi, call the properties of temp instead of this (or change the signature of multi to be multi() { as sum is):

let temp = {
  a: 10,
  b: 20,
  sum() {
    console.log('running `sum`:', 'this === window?', this === window);
    console.log(this.a, this.b, this.a + this.b);
    return this.a + this.b;
  },
  multi: () => {
    console.log('running `multi`:', 'temp === window?', temp === window);
    console.log(temp.a, temp.b, temp.a * temp.b);
    return temp.a * temp.b;
  }
};

console.log(temp.sum());
console.log(temp.multi());
phentnil
  • 2,195
  • 2
  • 14
  • 22
0

Arrow function expressions should not be used as methods as they do not have their own bindings to this according to MDN. It is called "lexical this". Normally, traditional functions bind "this" to the object (hence this.a means 10). If you use "this" in arrow function, it would mean the global object 'Window'. Therefore, it became undefined * undefined which is NaN.

llo
  • 136
  • 7