Home › Learn › JavaScript › Making decisions

if and else

Lesson 7 of 40. Run a block only when a condition holds.

if (condition) { ... } runs the block when the condition is true; else { ... } runs another block otherwise. The parentheses around the condition and the braces around the block are the syntax; indentation is for people.

A function that decides something usually returns from inside the branches. return ends the function immediately, so anything after an if that returned only runs when the condition was false, which often makes a trailing return do the job of else.

function sign(n) {
  if (n < 0) {
    return "negative";
  }
  return "not negative";
}
console.log(sign(-4));

Your task

Write describeTemp(c) that returns "cold" below 10, "mild" below 25, and "hot" otherwise.

Hint 1

Check the coldest case first and return; then the next.

Hint 2

Three outcomes need two conditions; the last outcome is whatever is left.

Show the solution
function describeTemp(c) {
  if (c < 10) {
    return "cold";
  }
  if (c < 25) {
    return "mild";
  }
  return "hot";
}

    Runs in an isolated web worker in this tab; nothing is sent anywhere.