Back
LearnJavaScript From ZeroHow does a program make decisions?

How does a program make decisions?

2 min read

Life is full of "if this, then that"

If it rains, then take an umbrella. If you are hungry, then eat. Programs think in exactly this way. We call it an if statement.

let age = 18;

if (age >= 18) {
  console.log("You can vote");
}

Read it plainly: "if age is greater than or equal to 18, then print 'You can vote'." The part inside ( ) is a question that is either true or false. If it is true, the code inside { } runs. If it is false, that code is skipped.

What if the condition is false?

That is where else comes in — it is the "otherwise" path.

let age = 15;

if (age >= 18) {
  console.log("You can vote");
} else {
  console.log("Too young, wait a bit");
}

Only one of the two will ever run. Never both.

How do I check more than two cases?

Use else if in the middle. JavaScript checks each one from top to bottom and stops at the first true one.

let marks = 72;

if (marks >= 90) {
  console.log("Grade A");
} else if (marks >= 60) {
  console.log("Grade B");
} else {
  console.log("Keep trying");
}

Here marks is 72, so the first check (90 or more) is false, the second (60 or more) is true → it prints "Grade B" and stops.

The comparison tools you will use daily

  • > greater than, < less than
  • >= greater or equal, <= less or equal
  • === exactly equal (use this to compare two things)
  • !== not equal

Be careful: use === (three equals) to compare, not = (one equals). A single = gives a value to a variable; three === checks whether two things are equal. Mixing these two up is a classic beginner trap.

Now your programs can think. Next, we will make them tireless — doing repetitive work for us without complaining.

Tip