Skip to the content.

Homework

Homework for classes and methods lessons.

Homework

JavaScript Classes and Methods - Interactive Homework

In this notebook, you will learn about classes and methods in JavaScript. After the lesson, complete the tasks by editing the code cells.

What are Classes and Methods?

  • Class: A blueprint for creating objects with properties and methods.
  • Method: A function inside a class that defines an object’s behavior.

Example: Class for food

Below is an example of a JavaScript class for creating different foods. The class has:

  1. A constructor to initialize properties (brand and model).
  2. Two methods (displayInfo and start) to define behaviors.
%%js
// Fridge Mini-Game: Enhanced with scores and quality feedback
//place class + constructor here
class fridge {
  constructor() {
    // Array of items in the fridge with their scores
    this.fridgeItems = [ //Write in ten items found in a fridge and assign them a value of 1-10 (values can repeat)
      { name: "Piece of pizza", score: 10 },
      { name: "apple", score: 9 },
      { name: "cake", score: 7 },
      { name: "ice cream", score: 5 },
      { name: "milk", score: 4 },
      { name: "cheese", score: 3 },
      { name: "orange juice", score: 2 },
      { name: "orange", score: 1 },
      { name: "hot dog", score: 11 },
      { name: "chicken ", score: 6 } // Its more fun if it FUNNY
    ];
  }
  // Method to pick a random item from the fridge
  getRandom() {
    let random = Math.floor(Math.random() * this.fridgeItems.length);
    return this.fridgeItems[random];
  }
  // Method to classify the find based on its score
  classifyFind(score) { // Create an if -> return -> else -> return loop using youe scoring system to create an output of good, meh, bad
    if(score >= 9){
      return "good";
    }
    else if(score >= 5){
      return "meh";
    }
    else{
      return "bad";
    }
  }
  // Reference method to start the game (Some fill in the blank)
  start() {
    console.log("game started"); // Write a response
    const item = this.getRandom();
    console.log(`item is  ${item.name}`); //fill in the () with a phrase on the item and a reference to the item
    // Get feedback based on the item's score (unchanged you only need to fix the {} )
    // find and fix the misisng pieces
    const feedback = this.classifyFind(item.score);
    console.log(`It is ${feedback} Score: ${item.score}`);
  }
}
// Create an instance of the game  hint: const.
const fridgeGame = new fridge();
// Start the game by calling the play method hint .play
fridgeGame.start()
<IPython.core.display.Javascript object>