JavaScript Coding Challenge: Color Ghost

Islam AboamhIslam Aboamh
2 min read

One fun and beginner-friendly JavaScript exercise is the "Color Ghost" problem. It tests your understanding of object constructors and random selection in arrays. Let's dive in!


🎯 Problem Statement

Create a constructor function Ghost that randomly assigns one of the following colors to a new Ghost object when it's instantiated:

  • "white"

  • "yellow"

  • "purple"

  • "red"

There are no parameters passed when creating the object. When a new Ghost is created, its .color property should be one of the four above, chosen at random.

Example:

let ghost = new Ghost();
console.log(ghost.color); // Outputs: "white", "yellow", "purple", or "red"

Each new Ghost object will get a color randomly assigned at creation time.


🧠 Understanding the Requirements

Let's break down what we need to do:

  1. Use a constructor function (function Ghost() {}).

  2. Define a fixed list of possible colors.

  3. Randomly select one color from that list.

  4. Assign the selected color to a color property on the newly created object.


🧪 How Random Selection Works in JavaScript

To randomly select an item from an array, you can use:

array[Math.floor(Math.random() * array.length)];
  • Math.random() generates a decimal between 0 (inclusive) and 1 (exclusive).

  • Multiplying that by array.length gives a number between 0 and just under the length of the array.

  • Math.floor() rounds it down to a valid array index (0 to length - 1).


✅ Final Solution

Here's the full solution using a constructor function:

let Ghost = function() {
  const colors = ["white", "yellow", "purple", "red"];
  this.color = colors[Math.floor(Math.random() * colors.length)];
};

🧪 Example Usage

let ghost1 = new Ghost();
console.log(ghost1.color); // could be "purple"

let ghost2 = new Ghost();
console.log(ghost2.color); // could be "red"

Each time you create a new ghost, its color is randomly picked from the predefined list.


🧩 Bonus: ES6 Class Version (Optional)

If you're familiar with ES6 syntax, here's how the same thing looks using a class:

class Ghost {
  constructor() {
    const colors = ["white", "yellow", "purple", "red"];
    this.color = colors[Math.floor(Math.random() * colors.length)];
  }
}

🚀 Conclusion

The "Color Ghost" problem is a great way to get comfortable with constructor functions, random selection from arrays, and object creation in JavaScript. Whether you're prepping for interviews or just building your JavaScript chops, exercises like this help solidify key programming concepts.

Happy coding! 👻

0
Subscribe to my newsletter

Read articles from Islam Aboamh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Islam Aboamh
Islam Aboamh

Inventive Front-End Developer with experience building responsive websites and apps in a fast-paced, collaborative environment. Talented in HTML/CSS/JavaScript/React.js and Next.js.