Created
May 21, 2023 20:33
-
-
Save kironroy/6241a908819145b15bff321c442b1c63 to your computer and use it in GitHub Desktop.
Optional chaining and nullish coalescing operator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const weekDays = ['mon', 'tues', 'wed', 'thu', 'fri', 'sat', 'sun']; | |
const openingHours = { | |
[weekDays[3]]: { | |
open: 12, | |
close: 22, | |
}, | |
fri: { | |
open: 11, | |
close: 23, | |
}, | |
sat: { | |
open: 0, // Open 24 hours | |
close: 24, | |
}, | |
}; | |
const restaurant = { | |
name: "Vini's Curry House", | |
location: '123 Gora Way, Mumbai, India', | |
categories: ['Punjabi', 'Bengali', 'Madras', 'Neplai'], | |
starterMenu: ['Samosa', 'Pakora', 'Nan', 'Kebab'], | |
mainMenu: ['Dosa', 'Chicken Madras', 'Tandoori Halibut'], | |
// ES6 enhanced object literals | |
openingHours, | |
// new way of writing functions | |
order(starterIndex, mainIndex) { | |
return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]]; | |
}, | |
orderDelivery({ starterIndex = 1, mainIndex = 0, time = '24.07', address }) { | |
console.log( | |
`Order received! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]} will be delivered ${address} at ${time}. ` | |
); | |
}, | |
}; | |
const menu = [...restaurant.starterMenu, ...restaurant.mainMenu]; | |
// for of loop | |
// for (const item of menu) console.log(item); | |
// destructuring arrays | |
for (const [i, el] of menu.entries()) { | |
console.log(`${i + 1}: ${el}`); | |
} | |
// console.log([...menu.entries()]); | |
// optional chaining | |
console.log(restaurant.openingHours?.mon?.open); // undefined | |
console.log(restaurant.openingHours.fri?.open); // opens at 11 | |
// no monday prop | |
// if (restaurant.openingHours.mon) | |
// console.log(restaurant.openingHours.mon.open); | |
// fri prop | |
// if (restaurant.openingHours.fri) | |
// console.log(restaurant.openingHours.fri.open); | |
// use case of optional chaining and nullish coalescing operator | |
const days = ['mon', 'tues', 'wed', 'thu', 'fri', 'sat', 'sun']; | |
for (const day of days) { | |
const open = openingHours[day]?.open ?? 'closed'; | |
console.log(`On ${day}, we open at ${open}`); | |
} | |
// optional chaining for methods | |
console.log(restaurant.order?.(0, 1) ?? 'method does not exist'); | |
console.log(restaurant.orderPakora?.(0, 1) ?? 'method does not exist'); | |
// optional chaining for arrays | |
const users = [{ name: 'Vini', email: 'vini@voice.com' }]; | |
console.log(users[0]?.name ?? 'user array empty'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment