let foodPlace = {
orderBurger: function(arg1, arg2, arg3) {
return `Your burger with ${arg1}, ${arg2} and ${arg3} is ready`
},
orderPasta: function(arg1, arg2, arg3) {
return `Your pasta with ${arg1}, ${arg2} and ${arg3} is ready`
}
}
console.log(foodPlace.orderBurger?.('cheese', 'lettuce', 'pickles') ?? "Method not found");
console.log(foodPlace.orderPasta?.('cheese', 'tomato sauce', 'basil')) ?? "Method not found";
When I tried running the above code on my local machine, it executed as expected without any issues.
NOTE: The output of both console.log statements is different.
If you run these commands in the developer tools console, the results may vary.
For the first console.log statement -
console.log(foodPlace.orderBurger?.('cheese', 'lettuce', 'pickles') ?? "Method not found");
the expected result will be printed since the string is returned by the orderBurger method and the Nullish coalescing operator checks that the left side of the expression is NOT null or undefined. Therefore, the console will display -
Your burger with cheese, lettuce and pickles is ready
However, for the second console.log statement -
console.log(foodPlace.orderPasta?.('cheese', 'tomato sauce', 'basil')) ?? "Method not found";
pay attention to the closing parenthesis after the console.log. In this case, the output will be -
Your pasta with cheese, tomato sauce and basil is ready
"Method not found"
The orderPasta method functions correctly and returns a string, which is then passed to the console log method. As the log method does not return anything (void), it evaluates as undefined, causing the Nullish coalescing operator to check the right side as well.
I hope this explanation clarifies things.