Adventure Game Example

Suppose you are building an adventure game where players can collect various items and equipment as they progress through the game. You could use the nullish coalescing operator to provide default values for the player's inventory if the inventory is null or undefined, like this:

class Player {
  constructor() {
    this.inventory = null;
  }

  addToInventory(item) {
    this.inventory = this.inventory ?? [];
    this.inventory.push(item);
  }

  getInventory() {
    return this.inventory ?? [];
  }
}

let player = new Player();

player.addToInventory('Sword');
player.addToInventory('Shield');

console.log(player.getInventory()); // ['Sword', 'Shield']

In this example, the addToInventory method uses the nullish coalescing operator to initialize the inventory property to an empty array if it is null or undefined. This ensures that the inventory property is always an array, even if the player does not have any items in their inventory yet.

The getInventory method also uses the nullish coalescing operator to return an empty array if the inventory property is null or undefined. This allows the player to safely access their inventory without having to check for its existence first.

Using the nullish coalescing operator in this way can make it easier to manage the player's inventory in the adventure game, and can help to avoid potential errors or issues that might arise if the inventory property is null or undefined.

Last updated