i am just learning about this combo of Optional chain and Nullish coalescing.
Here is the object
JavaScript
x
25
25
1
const restaurant = {
2
name_: 'Classico Italiano',
3
location: 'Via Angelo Tavanti 23, Firenze, Italy',
4
categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
5
starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
6
mainMenu: ['Pizza', 'Pasta', 'Risotto'],
7
8
openingHours: {
9
thu: {
10
open: 12,
11
close: 22,
12
},
13
fri: {
14
open: 11,
15
close: 23,
16
},
17
sat: {
18
open: 0, // Open 24 hours
19
close: 24,
20
},
21
},
22
orderPizza(ing1, ing2) {
23
console.log(`you have ordered your pizza with ${ing1} and ${ing2}`);
24
}};
25
as i am trying to check if the method exist,it is printing out both of them anyway.what am i doing wrong?
JavaScript
1
2
1
console.log(restaurant.orderPizza?.('some', 'something') ?? 'no method exist');
2
Advertisement
Answer
Perhaps return a value from the function otherwise it has an undefined value:
JavaScript
1
13
13
1
const restaurant1 = {
2
name_: 'Classico Italiano',
3
orderPizza(ing1, ing2) {
4
return `you have ordered your pizza with ${ing1} and ${ing2}`;
5
}
6
};
7
8
const restaurant2 = {
9
name_: 'Other',
10
};
11
12
console.log(restaurant1.orderPizza?.('some', 'something') ?? 'no method exist');
13
console.log(restaurant2.orderPizza?.('some', 'something') ?? 'no method exist');