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.