0

I have a method:

const objT2 = {
  calcAge(year) {
    console.log(2022 - year);
  },
};

but when I use the nullish coalescing both parts is being executed.

objT2.calcAge(1990) ?? console.log(`method not found`);
//output => 32    method not found
  • 1
    Calling `calcAge(1990)` doesn't `return` anything, so by default `undefined` is returned. The second opreand of `??` is evaluated if the first operand (ie: the return value of `calcAge()`) is `null` or `undefined`. – Nick Parsons Feb 12 '22 at 05:28
  • Logging and returning are two different things. Logging is a side-effect the occurs as part of running your function, returning is the actual value that your function "outputs"/evaluates to once called. Maybe you meant to do: `return 2022 - year` instead of `console.log(2022 - year)`. – Nick Parsons Feb 12 '22 at 05:29

1 Answers1

0

first you are calling calcAge method with 1990. so by calling it, the method gets executed objT2.calcAge(1990). this calculated 2022 - 1990 which is 32 and then logs it to the console. then this method returns undefined which gets evaluated as the left hand operand of the ?? operator. As this operator sees the left hand side is returning a nullish value (null or undefined), it goes on to execute the right hand side which logs method not found as well.

Sina
  • 379
  • 2
  • 9