site logo

Master JavaScript — Build, Create, and Innovate


Category: (All)
❮  Go Back

05. JavaScript Conditionals & Logic: if, switch, Ternary, Booleans & Logical Operators

Introduction

Control flow is what lets your JavaScript code make decisions. Conditionals like if, else, switch, and logical operators enable branching and complex logic. In this guide you'll learn:

  1. Boolean values and truthiness
  2. if / if-else statements
  3. The ternary operator
  4. switch statements
  5. Logical operators (&&, ||, !)

Understanding these tools allows you to direct program execution based on conditions.


1. Booleans & Truthiness / Falsiness

1.1 The Boolean Type

In JavaScript, Boolean is a primitive type with exactly two values: true and false. These are used in conditions to drive logic. ([w3schools.com/js/js_booleans.asp])

1.2 Truthy and Falsy Values

Beyond strict Booleans, JavaScript considers certain values as truthy (treated like true) or falsy (treated like false) in conditional contexts:

Falsy values include:

  1. false
  2. 0
  3. "" (empty string)
  4. null
  5. undefined
  6. NaN

Everything else is truthy, e.g. nonempty strings, nonzero numbers, objects, arrays, etc.

Example:

if ("hello") {
console.log("This is truthy");
}
if (0) {
console.log("Won’t run — 0 is falsy");
}

Use truthiness understanding to write cleaner code.


2. The if Statement

The simplest conditional structure in JavaScript is the if statement:

if (condition) {
// code executes if condition is true
}

Example:

let hour = 10;
if (hour < 12) {
console.log("Good morning!");
}

If the condition evaluates to true, the code block runs; otherwise, it’s skipped.


3. if … else

You can provide an alternative path when the if condition fails:

if (condition) {
// runs when true
} else {
// runs when false
}

Example:

let hour = 18;
if (hour < 12) {
console.log("Good morning!");
} else {
console.log("Good evening!");
}


4. if … else if … else

To test multiple conditions in sequence:

if (condition1) {
// when condition1 true
} else if (condition2) {
// when condition2 true
} else {
// default case
}

Example:

let hour = 15;

if (hour < 12) {
console.log("Good morning");
} else if (hour < 18) {
console.log("Good afternoon");
} else {
console.log("Good evening");
}


5. The Ternary Operator

For concise conditional expressions, JavaScript provides the ternary operator (condition ? exprIfTrue : exprIfFalse). It is useful for simple if-else logic in a single line.

Example:

let age = 20;
let drink = age >= 18 ? "Beer" : "Juice";
console.log(drink); // "Beer"

You can even nest ternary operators, though readability may suffer if overused. ([w3schools.com/js/js_if_ternary.asp])


6. switch Statement

For comparing one value against many possible matches, switch is often cleaner than many else if blocks.

switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// fallback code
}

Example:

let day = 3;
let dayName;

switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Unknown";
}
console.log(dayName);

Important: always include break (unless intentional fallthrough) to prevent execution from continuing into next cases. ([w3schools.com/js/js_switch.asp])


7. Logical Operators: &&, ||, !

Logical operators let you combine or invert Boolean expressions.

  1. && (AND) — true if both operands are truthy
  2. || (OR) — true if at least one operand is truthy
  3. ! (NOT) — negates the truth value

Examples:

let age = 25;
let hasID = true;

if (age >= 18 && hasID) {
console.log("Entry allowed");
}

let hour = 20;
if (hour < 10 || hour > 18) {
console.log("Office is closed");
}

let isOpen = false;
console.log(!isOpen); // true

Logical operators are essential for combining complex conditions. ([w3schools.com/js/js_logical.asp])


8. Putting It All Together

Example combining multiple concepts:

let score = 85;

if (score >= 90) {
console.log("Grade A");
} else if (score >= 75) {
console.log("Grade B");
} else if (score >= 60) {
console.log("Grade C");
} else {
console.log("Fail");
}

// Or using ternary (for simpler condition)
let result = score >= 60 ? "Pass" : "Fail";
console.log(result);

// Logical operator example
let age = 30, isMember = true;
if (age >= 18 && isMember) {
console.log("Allowed");
} else {
console.log("Not allowed");
}


Best Practices & Tips

  1. Use === / !== for comparisons to avoid type coercion surprises.
  2. Favor if / else if / else or switch when readability matters.
  3. Use the ternary operator only for simple conditions to keep code legible.
  4. Avoid overly deep nesting of conditionals—refactor with functions when logic becomes complex.
  5. Remember JavaScript’s truthy/falsy rules to avoid unintended behavior.


Conclusion

Conditionals and logical operators are the heart of decision-making in JavaScript. Mastering them enables dynamic, flexible, and robust code paths. Once you are comfortable with these, the next steps are loops, functions, and working with events and the DOM.

05. JavaScript Conditionals Logic if switch Ternary Booleans Logical Operators

coldshadow44 on 2025-10-12



(0)





Showing comments related to this post.




Member's Sites: