Platform Game Example

Let's say we are creating a platform game where the player can collect coins and power-ups. We want to create a function that checks if the player is currently standing on a coin or a power-up, and returns the corresponding value.

let player = { x: 10, y: 20 };
let coins = [{ x: 5, y: 25 }, { x: 12, y: 20 }, { x: 15, y: 30 }];
let powerUps = [{ x: 8, y: 22 }, { x: 18, y: 25 }, { x: 20, y: 15 }];

// Using explicit return
function checkCollectible() {
  for (let i = 0; i < coins.length; i++) {
    if (player.x === coins[i].x && player.y === coins[i].y) {
      return "coin";
    }
  }
  for (let i = 0; i < powerUps.length; i++) {
    if (player.x === powerUps[i].x && player.y === powerUps[i].y) {
      return "power-up";
    }
  }
  return "none";
}

let collectible = checkCollectible();
console.log(collectible); // Output: "coin"

We can use implicit return to make the code more concise, by using an arrow function and returning the value using the shorthand syntax:

let checkCollectible = () => 
  coins.find(coin => player.x === coin.x && player.y === coin.y) ? "coin" :
  powerUps.find(powerUp => player.x === powerUp.x && player.y === powerUp.y) ? "power-up" : "none";

console.log(checkCollectible()); // Output: "coin"

In this example, the function checkCollectible is an arrow function that check if the player is standing on a coin by using the find() method of the coins array, if the find method returns a value, it returns "coin", otherwise, it check for a power-up by using the find() method of the powerUps array, if the find method returns a value, it returns "power-up" otherwise it returns "none".

It is important to note that the find() method returns the value of the first element in the array that satisfies the provided testing function, and ? : operator is a shorthand of a if else statement that return the first value if the statement is true, otherwise returns the second value.

In summary, implicit return can make the code more concise by using arrow functions and shorthand syntax, it can help to better readability of the code, make it more maintainable, and ease the understanding of the game logic.

Last updated