JuanDraper
JuanDraper

Reputation: 49

Condensing several if statements into a for and an if

Is there a way to condense these four if statements into a for loop and with a single if condition? I was told that there is a way but I can only think of multiple else if statements.

function New() {
  if (foodInOven == true) {
    timeOfCooking += 1;
  }
  if (timeOfCooking == 10) {
    console.log("cooked pasta");
  } else if (timeOfCooking == 15) {
    console.log("burning pasta!");
  } else if (timeOfCooking == 20) {
    console.log("pasta burnt!!");
  }
}

Upvotes: 0

Views: 59

Answers (1)

Nick
Nick

Reputation: 16576

One option could be to have a lookup for your times and, if there's a value, log it to the console.

const cookingLookup = {
  10: "cooked pasta",
  15: "burning pasta!",
  20: "pasta burnt!!"
}

function New() {
  if (foodInOven == true) {
    timeOfCooking += 1;
  }
  if (cookingLookup[timeOfCooking]) {
    console.log(cookingLookup[timeOfCooking]);
  }
}

Upvotes: 5

Related Questions