Nullish Coalescing Operator (??) (ES2020)

  • almost like the || operator, but it works with nullish values instead of falsy values
  • Nullish values: only null and undefined
  • its precedence is directly below || and directly above the ternary operator
  • using ?? will fix the problem noted in the final || example from short_circuiting.md:
    • what happens is that the wrong value is returned when we have 0 guests at the restaurant because 0 is a falsy value so the evaluation continues and 10 is returned --- which is not what we want
const restaurant = {
  name: 'Classico Italiano',
  location: 'Via Angelo Tavanti 23, Firenze, Italy',
  categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
  starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
  mainMenu: ['Pizza', 'Pasta', 'Risotto'],
  operatingHours: {
    thu: {
      open: 12,
      close: 22,
    },
    fri: {
      open:11,
      close: 23,
    },
    sat: {
      open: 0,  // open 24 hours
      close:24
    },
  },
  order: function(starterIndex, mainIndex) {
    return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]]
  },
  orderDelivery: function ({
                             starterIndex = 1,
                             mainIndex = 0,
                             time = '20:00',
                             address,
                           }) {
    console.log(`Order recieved! ${this.starterMenu[starterIndex]}  and ${this.mainMenu[mainIndex]} will be delivers to ${address} at ${time}`)
  },
  orderPasta: function (ing1, ing2, ing3) {
    console.log(`Here is your delicious pasta with ${ing1}, ${ing2}, and ${ing3}.`)
  },
  orderPizza: function (mainIngredient, ...additionalIngredients) {
    // just going to log them here, but really you'd do something with the ingredients
    console.log(mainIngredient)
    console.log(additionalIngredients)
  },
}
  • the problem as described above:
    restaurant.numGuests = 0
    const guests = restaurant.numGuests || 10
    console.log(guests)      // 10
  • now using ??
    restaurant.numGuests = 0
    const guests = restaurant.numGuests ?? 10
    console.log(guests)      // 0    
    • now the falsy values that aren't nullish are treated as truthy, so 0 is returned, which is what we want

Copyright © 2022