JavaScript if...else statements run different code depending on whether a condition is truthy or falsy. Use if for the first condition, optional else if branches for additional conditions, and else as the fallback.
Basic syntax:
if (condition) {
// runs when condition is truthy
} else {
// runs when condition is falsy
}
A condition does not have to literally be true or false; JavaScript converts the tested value using Boolean rules.
Use if when code should run only when a condition is satisfied and no alternative branch is required.
const temperature = 32;
if (temperature > 30) {
console.log("It is hot");
}
The else branch runs when the if condition is falsy.
const age = 16;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
The original tutorial used a confirmation dialog as a practical branch example. The same logic can be written clearly with a Boolean result:
const satisfied = window.confirm("Are you satisfied with this tutorial?");
if (satisfied) {
window.alert("Thank you");
} else {
window.alert("Please share your feedback");
}
See the dedicated confirm dialog tutorial.
Use an else if chain when conditions are mutually exclusive and should be tested in order.
const score = 82;
if (score >= 90) {
console.log("A");
} else if (score >= 75) {
console.log("B");
} else if (score >= 60) {
console.log("C");
} else {
console.log("Needs improvement");
}
Order matters. Put more specific or higher-threshold conditions before broader ones.
Falsy values include false, numeric zero, an empty string, null, undefined, and NaN. Most other values are truthy.
const name = "";
if (name) {
console.log(`Hello ${name}`);
} else {
console.log("Name is empty");
}
0 or an empty string is valid data, do not use a generic truthiness check when you actually need to distinguish null or undefined.const age = 22;
const hasId = true;
if (age >= 18 && hasId) {
console.log("Condition satisfied");
}
Use comparison operators for value checks and logical operators to combine conditions.
This preserves the original numeric comparison example with modern output.
const n1 = 4;
const n2 = 6;
if (n2 > n1) {
console.log("n2 is greater than n1");
} else {
console.log("n2 is not greater than n1");
}
Client-side conditions can give immediate feedback. Read the input value, test its length, and write plain text to a status element.
<label for="nameInput">Name</label>
<input id="nameInput" type="text">
<button id="checkButton" type="button">Check</button>
<div id="message" aria-live="polite"></div>
const input = document.getElementById("nameInput");
const button = document.getElementById("checkButton");
const message = document.getElementById("message");
button.addEventListener("click", () => {
if (input.value.trim().length < 2) {
message.textContent = "Enter at least 2 characters.";
} else {
message.textContent = "Input length is valid.";
}
});
The original page used inline onclick and innerHTML. An event listener and textContent are clearer and safer for plain-text feedback. See string length.
An if can appear inside another branch, but deeply nested logic becomes hard to scan.
const loggedIn = true;
const role = "editor";
if (loggedIn) {
if (role === "editor") {
console.log("Show editing tools");
}
}
When nesting grows, consider guard clauses, helper functions, or a data-driven design.
Inside a function, an early return can handle invalid or exceptional cases before the main path, reducing indentation.
function getDiscount(total) {
if (!Number.isFinite(total) || total < 0) {
return 0;
}
if (total >= 1000) {
return 0.1;
}
return 0;
}
For a short expression that chooses between two values, the conditional operator can be concise.
const age = 20;
const label = age >= 18 ? "Adult" : "Minor";
console.log(label);
Do not turn a long multi-branch decision into nested ternary operators merely to save lines; if...else is often easier to read.
JavaScript allows some one-line if statements without braces, but consistently using braces reduces maintenance mistakes when another statement is later added.
if (isReady) {
start();
}
A common bug is writing = inside a condition when === was intended.
let status = "ready";
if (status === "ready") {
console.log("Start");
}
// if (status = "ready") { ... } // assigns instead of comparing
Browser-side if statements are useful for user experience but can be modified or bypassed by the user. Authorization, permissions, prices, and other security-sensitive rules must also be enforced on the server.
= instead of a comparison operator.else if conditions.Continue with switch, loops, for loops, comparisons, and logical operators.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.