if, else and the Ternary

Choose between branches with if / else if / else, and pick a value with condition ? a : b.

JavaScript · beginner · 5 min · 8 steps · free

What you'll learn

Conditionals.js

function grade(score) {
  if (score >= 90) {
    return 'A';
  } else if (score >= 75) {
    return 'B';
  }
  return 'C';
}

const result = grade(82);
const label = result === 'A' ? 'excellent' : 'good';
console.log(result, label);

Step by step

  1. Before the first line runs, JavaScript reads the whole file: the function grade already exists. This is called hoisting.
  2. JavaScript calls grade with score = 82.
  3. 82 >= 90 is false, so JavaScript moves on to the else if.
  4. score >= 75 is true, so the if-block runs.
  5. return ends the function at once: the last line, return "C", never runs.
  6. grade() has finished, so its variables are gone. The value it returned, "B", is stored in result.
  7. The ternary condition ? a : b picks a value: result is not "A", so label = "good".
  8. It prints B good.

Common mistakes

Best practices

Key takeaways

Check yourself

grade(95)?

Answer: "A"

true ? 1 : 2?

Answer: 1

·

More in The Basics