Action Game Example

Optional Chaining explained

Suppose you are building an action game where players can collect different types of weapons and equipment. You could use optional chaining to safely access and use a player's equipped weapon without having to check if the player has a weapon equipped at all.

First, you would define a Player class with a weapon property that represents the player's currently equipped weapon:

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

  equipWeapon(weapon) {
    this.weapon = weapon;
  }
}

Then, you could define a Weapon class with a use method that represents the action of using the weapon:

class Weapon {
  constructor(name) {
    this.name = name;
  }

  use() {
    console.log(`Using weapon: ${this.name}`);
  }
}

Now, suppose you want to allow the player to use their equipped weapon. Without optional chaining, you would have to check if the player has a weapon equipped before using it, like this:

let player = new Player();

if (player.weapon) {
  player.weapon.use();
}

With optional chaining, you can simplify this code by using the ?. operator to safely access the use method of the weapon property, like this:

player.weapon?.use();

This can be useful in an action game where players may not always have a weapon equipped or the player character may have different abilities or actions depending on their equipped weapon. You can safely access and use the player's equipped weapon using optional chaining without having to manually check for its existence.

Last updated