Trivia Game example

Let's say we are creating a trivia game that keeps track of the player's score and name.

Here is an example of how the player object can be defined using traditional syntax:

let playerName = "John";
let playerScore = 0;

let player = {
  name: playerName,
  score: playerScore
};
console.log(`Player: ${player.name} Score: ${player.score}`); // Output: "Player: John Score: 0"

With the shorthand syntax, you can define the object properties in a more concise way:

let playerName = "John";
let playerScore = 0;

let player = {
  name: playerName,
  score: playerScore
};
console.log(`Player: ${player.name} Score: ${player.score}`); // Output: "Player: John Score: 0"

We can also use shorthand when defining methods, for example, we can create a method that adds a point to the player's score:

let player = {
  name: "John",
  score: 0,
  addPoint(){
    this.score++;
  }
}
console.log(`Player: ${player.name} Score: ${player.score}`); // Output: "Player: John Score: 0"
player.addPoint();
console.log(`Player: ${player.name} Score: ${player.score}`); // Output: "Player: John Score: 1"

In this way, we can use object shorthand to make our code more readable and more maintainable, it can help us to avoid repeating ourselves when defining properties and methods, and make the code more concise.

Last updated