JavaScript if...else Statement

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.

Using a Simple if Statement Top ↑

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");
}

Using if...else Top ↑

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.

Testing Multiple Conditions with else if Top ↑

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.

Truthy and Falsy Conditions Top ↑

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");
}
Be precise: if 0 or an empty string is valid data, do not use a generic truthiness check when you actually need to distinguish null or undefined.

Combining Comparisons and Logical Operators Top ↑

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.

Checking Numbers with if...else Top ↑

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");
}

Checking the Length of User Input Top ↑

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.

Nested if Statements Top ↑

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.

Early Returns and Guard Clauses Top ↑

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;
}

Conditional (Ternary) Operator Top ↑

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.

Should You Use Braces for a Single Statement? Top ↑

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();
}

Assignment Is Not Comparison Top ↑

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

Client-Side Conditions Do Not Enforce Security Top ↑

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.

Common if...else Mistakes Top ↑

  • Using = instead of a comparison operator.
  • Relying on loose equality without understanding coercion.
  • Putting broad conditions before more specific else if conditions.
  • Using a truthiness test when zero or an empty string is valid.
  • Creating excessive nesting instead of simplifying the control flow.
  • Using client-side validation as the only security check.

Continue with switch, loops, for loops, comparisons, and logical operators.

Loops For Loop




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer