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");
}
Choose between several outcomes
Use else if when a decision has more than two possible paths. JavaScript checks each condition in order and runs the first matching block:
const score = 76;
if (score >= 90) {
console.log("Excellent");
} else if (score >= 70) {
console.log("Passed");
} else {
console.log("Try again");
}
Use a condition that states the rule
JavaScript converts values used as conditions to true or false. For beginner code, explicit comparisons often make the rule easier to understand:
if (cartItemCount > 0) {
console.log("Your cart has items");
}
Be aware that an empty string, 0, null and undefined are falsy, while an empty array and an empty object are truthy.
Assignment is different from comparison
A single equals sign = assigns a value. Three equals signs === compare two values without converting their types. For example, attempt = 10 assigns a value to a reassignable variable; attempt === 10 checks whether it equals ten.
JavaScript conditional questions
When should I use else if?
Use it when you need to test another condition after the preceding if condition was false. Put the most specific or highest-priority condition first.
Can I use a value directly as an if condition?
Yes. JavaScript converts it to a Boolean, but explicit comparisons such as count > 0 can make the intended rule clearer.