Free beginner tutorial

JavaScript Conditionals: if, else and Comparisons

Learn JavaScript if and else statements, Boolean conditions, strict comparisons and logical operators with practical examples.

Run code when a condition is true

An if statement runs its block when the condition evaluates to true. Add else for the alternative path.

const temperature = 18;

if (temperature >= 20) {
  console.log("Warm enough for a walk");
} else {
  console.log("Bring a jacket");
}

Compare values carefully

Use === to compare both value and type. For example, 5 === "5" is false because one value is a number and the other is a string.

Combine conditions

The logical AND operator && requires both conditions to be true. The logical OR operator || requires at least one condition to be true. Use parentheses when they make a longer condition easier to read.

const hasTicket = true;
const isAdult = true;

if (hasTicket && isAdult) {
  console.log("Entry allowed");
}
A condition should describe the decision clearly. Use Boolean variables with names that make the true and false cases easy to understand.