Control Flow

Conditional statements (if, else, else if

1. What Are Conditional Statements?

Conditional statements allow you to execute code based on conditions — they control flow and logic.

if (condition) {
// code runs if condition is true
} else if (anotherCondition) {
// runs if first is false, this is true
} else {
// runs if none of the above are true
}

2. if Statement

Executes a block of code only if a condition is true.

let age = 18;

if (age >= 18) {
console.log(“You are an adult.”);
}

  • If age is 18 or more, the message is printed.
  • If not, nothing happens.

3. else Statement

Provides an alternative block if the if condition is false.

let age = 16;

if (age >= 18) {
console.log(“You are an adult.”);
} else {
console.log(“You are a minor.”);
}

  • Outputs “You are a minor.”

4. else if Statement

Allows you to check multiple conditions in sequence.

let score = 85;

if (score >= 90) {
console.log(“Grade: A”);
} else if (score >= 80) {
console.log(“Grade: B”);
} else if (score >= 70) {
console.log(“Grade: C”);
} else {
console.log(“Grade: F”);
}

  • Only the first true condition block will run.

5. Comparison Operators in Conditions

Operator Meaning Example
== Equal (loose) x == “5”
=== Equal (strict) x === 5
!= Not equal (loose) x != “5”
!== Not equal (strict) x !== 5
> Greater than x > 10
< Less than x < 10
>= Greater or equal x >= 10
<= Less or equal x <= 10

Note: Always prefer strict equality (=== and !==) to avoid type coercion issues.

6. Example – Login Check

let username = “admin”;
let password = “1234”;

if (username === “admin” && password === “1234”) {
console.log(“Login successful”);
} else {
console.log(“Invalid credentials”);
}

7. Nested if Statements

You can nest one if inside another for more complex logic.

let temp = 25;

if (temp > 0) {
if (temp < 30) {
console.log(“Nice weather”);
}
}

8. Best Practices

  • Use === instead of == to avoid type coercion bugs.
  • Keep conditions simple and readable.
  • Use brackets {} even for one-line blocks to avoid logic errors.
  • Avoid deeply nested ifs — consider switch, functions, or guards.

Switch statement

The switch statement in JavaScript is used to execute one block of code among many based on the value of an expression. It offers a cleaner alternative to multiple if…else if conditions, especially when dealing with many fixed options.

What is the switch Statement?

The switch statement evaluates an expression and executes code based on the matching case. It helps simplify code and improve readability.

Syntax of JavaScript switch

switch (expression) {
case value1:
// Code to execute if expression === value1
break;
case value2:
// Code to execute if expression === value2
break;

default:
// Code to execute if no case matches
}

  • expression: A value or variable you want to compare.
  • case: Each possible match for the expression.
  • break: Ends the current case block. Without it, execution continues (fall-through).
  • default: Optional fallback if no match is found.

Example of switch Statement

let day = 3;
let dayName;

switch (day) {
case 1:
dayName = “Monday”;
break;
case 2:
dayName = “Tuesday”;
break;
case 3:
dayName = “Wednesday”;
break;
case 4:
dayName = “Thursday”;
break;
case 5:
dayName = “Friday”;
break;
case 6:
dayName = “Saturday”;
break;
case 7:
dayName = “Sunday”;
break;
default:
dayName = “Invalid day”;
}

console.log(dayName); // Output: Wednesday

Advantages of Using switch in JavaScript

  • Improves code readability
  • Faster execution for long conditional chains
  • Clear structure for handling many values of the same variable

Why Use break in Switch?

The break keyword prevents fall-through, where multiple case blocks execute unintentionally.

let color = “blue”;

switch (color) {
case “red”:
console.log(“Color is red”);
break;
case “blue”:
console.log(“Color is blue”);
break;
case “green”:
console.log(“Color is green”);
break;
default:
console.log(“Color not recognized”);
}

Without break, JavaScript will execute all statements after the matched case, even if they don’t match.

Grouping Multiple Cases Together

Sometimes different cases share the same code block:

let grade = “B”;

switch (grade) {
case “A”:
case “B”:
case “C”:
console.log(“You passed!”);
break;
case “D”:
case “F”:
console.log(“You failed.”);
break;
default:
console.log(“Invalid grade”);
}

switch vs if…else in JavaScript

Feature switch if…else
Best for Multiple equality checks Complex conditions, ranges
Readability High for many values Better for logic combinations
Type of comparison Strict (===) Can be any condition
Performance Slightly better for many cases Comparable

Tip: Use switch when comparing the same variable against multiple values,
and if…else when dealing with complex conditions or ranges.

Best Practices for Using switch

  • Use break in each case to avoid unwanted execution.
  • Always include a default case for unknown values.
  • Avoid complex expressions inside switch — keep it simple and readable.
  • Ideal for menus, input validation, status checks, etc.

Conclusion: Why Use the switch Statement in JavaScript?
The JavaScript switch statement is a clean, fast, and efficient way to handle multiple possible values for a single variable. Whether you’re building a web app, working on form validation, or setting up game logic, switch statements help keep your code readable and maintainable.

Truthy and falsy values

In JavaScript, every value has an inherent boolean value — either truthy or falsy — when used in a boolean context (e.g., inside if statements or logical operations).

Falsy Values

There are only 7 falsy values in JavaScript. These values evaluate to false when converted to a boolean.

Value Type Description
false Boolean Literal false
0 Number Zero
-0 Number Negative zero
0n BigInt Zero BigInt
“” String Empty string
null Object Represents no value
undefined Undefined Variable not assigned a value
NaN Number Not-a-Number

Example:

if (!0) {
console.log(“This is falsy”);
}
// Output: This is falsy

Truthy Values:

Everything else in JavaScript is considered truthy — it evaluates to true in a boolean context.

Example Value Description
“hello” Non-empty string
42 Any non-zero number
-42 Negative numbers too
[] Empty array
{} Empty object
function() {} Any function

Example:

if (“hello”) {
console.log(“This is truthy”);
}
// Output: This is truthy

Using Truthy/Falsy in Conditions

let name = “”;

if (name) {
console.log(“Name is set”);
} else {
console.log(“Name is empty”);
}
// Output: Name is empty

Common Pitfalls

0, “”, and null all evaluate to false, so be careful when checking values like:

let userInput = 0;

if (userInput) {
console.log(“Input provided”);
} else {
console.log(“No input”);
}
// Output: No input — even though userInput is 0

Fix using explicit check:

if (userInput !== null && userInput !== undefined) {
console.log(“Input provided”);
}

Boolean Conversion with Boolean() or !!

You can explicitly convert values:

Boolean(“”) // false
Boolean(“Hi”) // true
!!0 // false
!![1, 2, 3] // true

Summary Table:

Value Type Truthy/Falsy
false Boolean Falsy
0 Number Falsy
null Object Falsy
undefined Undefined Falsy
“abc” String Truthy
{} Object Truthy
[] Object Truthy
function(){} Function Truthy

Ternary operator

What is the Ternary Operator in JavaScript?

The ternary operator is a shortcut for if…else statements, used to return a value based on a condition. It’s also called the conditional operator.

It’s called “ternary” because it takes three operands.

Syntax of Ternary Operator

condition ? expressionIfTrue : expressionIfFalse;

  • condition: A boolean expression to evaluate
  • expressionIfTrue: Executes if the condition is true
  • expressionIfFalse: Executes if the condition is false

Basic Example:

let age = 18;
let access = (age >= 18) ? “Allowed” : “Denied”;

console.log(access); // Output: “Allowed”

This is equivalent to:

let access;
if (age >= 18) {
access = “Allowed”;
} else {
access = “Denied”;
}

Nested Ternary Operators

You can nest ternary operators, but it can hurt readability:

let score = 85;
let grade = (score >= 90) ? “A” :
(score >= 80) ? “B” :
(score >= 70) ? “C” :
“F”;

console.log(grade); // Output: “B”

  • Use parentheses or break into if…else for clarity when nesting.

Ternary Operator for Inline Actions

Commonly used for simple decisions inside expressions or JSX (e.g., in React):

console.log(isLoggedIn ? “Welcome back!” : “Please log in.”);

Important Notes

  • Ternary operators are expressions, not statements — they return values.
  • Best used for simple, concise conditions.
  • Avoid deeply nested ternaries — use if…else for better readability.

Real-world Use Case: Theme Toggle

let isDarkMode = true;
let theme = isDarkMode ? “Dark Theme Enabled” : “Light Theme Enabled”;

console.log(theme); // Output: “Dark Theme Enabled”

Best Practices:

Do Avoid
Use for concise logic Complex nested conditions
Use for returning values Long blocks of logic
Keep expressions short Actions with side effects

Summary:

  • Ternary operator simplifies simple if…else logic into a single line.
  • Ideal for value assignment and inline decisions.
  • Avoid using it for complex or multi-step logic.

Leave a Comment