I’m learning JS from one of Udemy courses where optional chaining is explained. I think I get it yet there is a strange outcome I cannot figure out. I’m literally starying at it for 30minutes and cannot see what is the issue here.
There is a restaurant object with methods:
order(starterIndex, mainIndex) {
return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
},
orderPizza(mainIngredient, ...otherIngredients) {
console.log(`Ordered pizza with ${mainIngredient} and additional: ${otherIngredients}`)
}
Then I use optional chaining on these methods :
console.log(restaurant.orderPizza?.('salami') ?? 'Method does not exist 1');
console.log(restaurant.order?.(0, 1) ?? 'Method does not exist 2');
console.log(restaurant.order?.(0, 1) ?? 'Method does not exist 3');
console.log(restaurant.orderRisotto?.(0, 1) ?? 'Method does not exist 4');
And as a result I got:
Ordered pizza with salami and additional:
Method does not exist 1
(2) ['Focaccia', 'Pasta']
(2) ['Focaccia', 'Pasta']
Method does not exist 4
Why Method does not exist 1 is printed since method exists and is executed? There are no issues with .order() method tho, what am I missing here? Is it because of return and .orderPizza() is more like a void? But this concept does not apply to JavaScript right? At least it was not introduced to me so far.
>Solution :
Is it because of return and .orderPizza() is more like a void?
Yes, that’s exactly what’s happening. Look at the following:
const x = null;
console.log('value of x is ' + (x ?? '??'));
const y = undefined;
console.log('value of y is ' + (y ?? '??'));
const z = 0;
console.log('value of z is ' + (z ?? '??'));
Since you don’t return anything from orderPizza(), then when you call orderPizza() ?? 'zzz' it will process the right side of the ??, as the left side is null/undefined.