Skip to content

JavaScript Tutorial Conditions

JavaScript if and else

Lesson 41 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

Programs need to make decisions: show the menu if the user is logged in, show an error if the field is empty. An if statement runs a block of code only when a condition is true.

script.js
JS
const age = 20;

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

The condition goes in parentheses. If it is true, the code inside the curly braces runs. If not, it is skipped.

else: the otherwise case

script.js
JS
const temperature = 12;

if (temperature > 25) {
  console.log("It is warm.");
} else {
  console.log("It is cool."); // → It is cool.
}

Exactly one of the two blocks runs.

A real example

index.html
HTML
<input id="age" type="number" placeholder="Your age">
<button id="check">Check</button>
<p id="result"></p>
<script>
  document.querySelector("#check").addEventListener("click", () => {
    const age = Number(document.querySelector("#age").value);
    const result = document.querySelector("#result");

    if (age >= 18) {
      result.textContent = "Welcome!";
    } else {
      result.textContent = "Sorry, this page is for adults.";
    }
  });
</script>

Always use curly braces

JavaScript allows an if without braces when there is a single statement:

script.js
JS
if (isReady) console.log("Go");

It works, but adding a second line later without braces is a classic bug. Using braces every time is safer.

The condition can be any expression

JavaScript converts it to true or false. See Truthy and Falsy. For comparing values, remember to use ===, as explained in Strict vs Loose Equality.

script.js
JS
const items = [];

if (items.length === 0) {
  console.log("Your cart is empty."); // → Your cart is empty.
}
warning
A semicolon after the condition
if (x > 5); ends the statement immediately, so the next block always runs. Never put a semicolon right after the parentheses.