Both the sides of nullish coalescing operator in JavaScript are being executed

1.7k views Asked by At
console.log(restaurant.orderPizza?.('onion','tomato','basil') ?? 'Method does not exist');

console.log(restaurant.orderRissotto?.('onion','tomato','basil') ?? 'Method does not exist'

orderPizza and orderRissotto are the two methods inside object restaurant.

When I log them using Nullish Coalesceing operator, the method output gets logged because method is available. However, second part, 'Method does not exist' also gets logged. What might be the reason?

Log:

Your pizza with onion, tomato and basil is ready
Method does not exist
2

There are 2 answers

0
Alberto On

the Null Safe returns null, and the Nullish coalescing operator will return the second piece if the first one is null || undefined... therefore if your method does not exists, the null safe will return null, and so the second part will be returned, but if the method exists but returns null || undefined value, the first part will be run, but the second part will be printed (since your method returns one of the value that Nullish coalescing use to determin if the second part should be returned)

0
jateen On

let restaurant = {
  orderPizza: function(arg1, arg2, arg3) {
    return `Your pizza with ${arg1}, ${arg2} and ${arg3} is ready`
  },
  orderRisotto: function(arg1, arg2, arg3) {
    return `Your risotto with ${arg1}, ${arg2} and ${arg3} is ready`
  }
}


console.log(restaurant.orderPizza?.('onion', 'tomato', 'basil') ?? "Method not found");

console.log(restaurant.orderRisotto?.('onion', 'tomato', 'basil')) ?? "Method not found";

Tried executing the above code snippet on my local machine, I was able to execute it properly as per expectation.

NOTE: Both the console.log statements are different.

If you are trying to execute these commands in the dev tools console, the results would be different.

For the first console.log statement -

console.log(restaurant.orderPizza?.('onion', 'tomato', 'basil') ?? "Method not found");

the result would be as per expectation, since the string is returned from the orderPizza method and the Nullish coalescing operator has the left side of the expression NOT null or undefined. Hence the console prints -

Your pizza with onion, tomato and basil is ready

But for the second console.log statement -

console.log(restaurant.orderRisotto?.('onion', 'tomato', 'basil')) ?? "Method not found";

notice the closing parenthesis for the console.log. This statement would print -

Your risotto with onion, tomato and basil is ready
"Method not found"

The orderRisotto method works as per expectation and results the string, which is then passed to the log method of the console. But since the log method is a void method, it returns undefined, which then makes the left side Nullish coalescing operator to be undefined and hence the right side is also evaluated.

I hope this answer helps.