Dig a hole game example

Let's say we are creating a game where the player digs a hole to find treasure. The treasure can be gold, silver or bronze and it is represented by an object like this

let treasure = {
  gold: 2,
  silver: 5,
  bronze: 8
}

We can use destructuring to extract the gold value from the treasure object and assign it to a variable:

let {gold} = treasure;
console.log(gold); // Output: 2

We can also use destructuring to extract multiple values from the treasure object and assign them to variables:

let {gold, silver, bronze} = treasure;
console.log(gold); // Output: 2
console.log(silver); // Output: 5
console.log(bronze); // Output: 8

We can use concatenation to create a string that describes the treasure found by the player:

let message = "You have found " + gold + " gold, " + silver + " silver and " + bronze + " bronze";
console.log(message); // Output: "You have found 2 gold, 5 silver and 8 bronze"

We can also use template literals instead of concatenation, template literals are string literals that allow embedded expressions. This can make the code more readable and less prone to errors:

let message = `You have found ${gold} gold, ${silver} silver and ${bronze} bronze`;
console.log(message); // Output: "You have found 2 gold, 5 silver and 8 bronze"

In this way, we can use destructuring and concatenation (or template literals) to extract specific values from an object and create a message that describes the treasure found by the player. This can help to make the code more readable and less prone to errors, by using destructuring and concatenation we can handle the logic of the game in a simpler and more intuitive way.

Last updated