Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Optional chaining working not as expected

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading