0
0
JavascriptHow-ToBeginner · 3 min read

How to Use If Else in JavaScript: Simple Guide with Examples

In JavaScript, use the if statement to run code when a condition is true, and else to run code when it is false. The syntax is if (condition) { ... } else { ... }, letting your program choose between two paths.
📐

Syntax

The if else statement lets you run different code based on a condition. The if part checks if a condition is true. If it is, the code inside its block runs. If not, the code inside the else block runs.

Here’s what each part means:

  • if: starts the condition check
  • (condition): a test that is true or false
  • { ... }: code to run if the condition is true
  • else: runs if the condition is false
  • { ... }: code to run if the condition is false
javascript
if (condition) {
  // code runs if condition is true
} else {
  // code runs if condition is false
}
💻

Example

This example checks if a number is positive or not. It prints a message based on the check.

javascript
const number = 5;

if (number > 0) {
  console.log("The number is positive.");
} else {
  console.log("The number is zero or negative.");
}
Output
The number is positive.
⚠️

Common Pitfalls

One common mistake is forgetting the curly braces { }, which can cause only the next line to be part of the if or else. Another is using = (assignment) instead of == or === (comparison) in the condition.

Always use === for strict comparison to avoid unexpected results.

javascript
let x = 10;

// Wrong: assignment instead of comparison
if (x = 5) {
  console.log("x is 5");
} else {
  console.log("x is not 5");
}

// Right: strict comparison
if (x === 5) {
  console.log("x is 5");
} else {
  console.log("x is not 5");
}
Output
x is 5 x is not 5
📊

Quick Reference

Use this quick guide to remember how if else works:

PartDescription
if (condition)Runs code if condition is true
elseRuns code if condition is false
{ ... }Code block to execute
=== vs ==Use === for strict equality check
Curly bracesAlways use to group multiple statements

Key Takeaways

Use if else to run code based on true or false conditions.
Always use curly braces { } to avoid mistakes with multiple lines.
Use === for strict comparison, not = which assigns values.
The else block runs only if the if condition is false.
If you only need one condition, else is optional.