JavaScript Roadmap — Day 10: Logical Operators

 

JavaScript · Day 10 of 180 · Beginner Phase

Logical Operators

Logical operators combine conditions and control the flow of your entire program. Master &&, ||, and ! — and you unlock the power to write intelligent, decision-making code.

Day 10 / 180
Beginner Phase
🕐 11 min read
💻 5 code examples
🎯 3 practice tasks

Imagine a security guard at a bank with three rules:

🔐 Entry allowed if: has valid ID AND is on the list → hasID && isOnList
🚪 Alert triggered if: door forced open OR alarm triggered → doorForced || alarmTriggered
🚫 Access denied if: NOT authorized → !isAuthorized

These three words — AND, OR, NOT — are the building blocks of all logic in every program ever written. JavaScript implements them as &&, ||, and !.

But here is what most tutorials miss — logical operators in JavaScript do not just return true or false. They return actual values. This behavior called short circuit evaluation is one of the most powerful and widely used patterns in modern JavaScript. By the end of this lesson you will use it every single day.

1. Logical Operators — Overview

JavaScript has three core logical operators. Each one combines or inverts boolean values to produce a result:

Operator Name Returns true when Example
&& AND Both sides are truthy age >= 18 && hasID
|| OR At least one side is truthy isAdmin || isModerator
! NOT The value is falsy !isLoggedIn

2. && — The AND Operator

&& returns true only when both conditions are true. If the first condition is false — it immediately stops and returns false without even checking the second condition. This is called short circuiting:

JavaScript — && AND Operator
// Basic AND
console.log(true  && true);   // true  ← both truthy
console.log(true  && false);  // false ← second is false
console.log(false && true);   // false ← first is false
console.log(false && false);  // false ← both false

// Real world — access control
const age       = 20;
const hasTicket = true;
const isBanned  = false;

const canEnter = age >= 18 && hasTicket && !isBanned;
console.log(canEnter); // true ✅

// Multiple conditions
const salary     = 80000;
const experience = 3;
const hasSkill   = true;

const eligible = salary > 50000 && experience >= 2 && hasSkill;
console.log(`Job eligible: ${eligible}`); // true

// && truth table
// true  && true  = true
// true  && false = false
// false && true  = false  ← stops here, never checks right
// false && false = false  ← stops here, never checks right

3. || — The OR Operator

|| returns true when at least one condition is true. If the first condition is true — it immediately stops and returns true without checking the second. This short circuiting behavior is the key to a very powerful pattern you will use every day:

JavaScript — || OR Operator
// Basic OR
console.log(true  || true);   // true
console.log(true  || false);  // true  ← first is true, stops
console.log(false || true);   // true  ← second is true
console.log(false || false);  // false ← both false

// Real world — role check
const isAdmin     = false;
const isModerator = true;
const isOwner     = false;

const canDelete = isAdmin || isModerator || isOwner;
console.log(canDelete); // true ← isModerator is true

// Default values with || (old way)
function greet(name) {
  const displayName = name || "Guest";
  console.log(`Hello, ${displayName}!`);
}
greet("Waheed"); // Hello, Waheed!
greet("");       // Hello, Guest! ← "" is falsy
greet();        // Hello, Guest! ← undefined is falsy

4. ! — The NOT Operator

! flips a boolean value — true becomes false and false becomes true. It also converts any truthy value to false and any falsy value to true. The double !! is a classic trick to convert any value to a boolean:

JavaScript — ! NOT Operator
// Basic NOT
console.log(!true);   // false
console.log(!false);  // true

// NOT with truthy/falsy values
console.log(!0);        // true  ← 0 is falsy
console.log(!"");       // true  ← "" is falsy
console.log(!null);     // true  ← null is falsy
console.log(!42);       // false ← 42 is truthy
console.log(!"hello");  // false ← string is truthy

// !! Double NOT — convert any value to boolean
console.log(!!0);        // false
console.log(!!"hello");  // true
console.log(!!null);     // false
console.log(!!42);       // true
console.log(!!"");       // false

// Real world — toggle state
let isMenuOpen = false;
isMenuOpen = !isMenuOpen; // toggle on
console.log(isMenuOpen);  // true
isMenuOpen = !isMenuOpen; // toggle off
console.log(isMenuOpen);  // false
Pro Tip #1 — !! is the Boolean() shortcut
Double NOT !! converts any value to its boolean equivalent — same as Boolean(value) but shorter. You will see !!value constantly in React codebases to check if something exists before rendering it.
Pro Tip #2 — ! is great for toggle buttons
The pattern isOpen = !isOpen is used in every UI component that has an on/off state — dropdown menus, modals, dark mode, sidebar toggles. It is one of the most common one-liners in frontend JavaScript.
Pro Tip #3 — Operator precedence matters
! has higher precedence than && which has higher precedence than ||. So !a && b || c is read as ((!a) && b) || c. When in doubt use parentheses to make your intent clear — (a && b) || c.

5. Short Circuit Evaluation — The Real Power 🔥

This is what most tutorials skip — and it is one of the most used patterns in modern JavaScript. Logical operators do not just return true or false. They return the actual value that caused them to stop evaluating:

JavaScript — Short Circuit Evaluation
// && returns the FIRST FALSY value or the LAST value
console.log(1 && 2 && 3);        // 3   ← all truthy, returns last
console.log(1 && 0 && 3);        // 0   ← stops at first falsy
console.log(null && "hello");     // null ← stops at null
console.log("hi" && "world");    // "world" ← all truthy

// || returns the FIRST TRUTHY value or the LAST value
console.log(0 || 1 || 2);        // 1    ← first truthy
console.log(null || undefined || "hi"); // "hi" ← first truthy
console.log(0 || "" || null);    // null ← all falsy, returns last
console.log("Waheed" || "Guest"); // "Waheed" ← first truthy

// Real world patterns using short circuit

// Pattern 1 — Default value with ||
const username = "" || "Guest";
console.log(username); // "Guest"

// Pattern 2 — Conditional execution with &&
const isLoggedIn = true;
isLoggedIn && console.log("Welcome back, Waheed!");
// only runs if isLoggedIn is truthy

// Pattern 3 — Safe property access with &&
const user = { name: "Waheed", address: null };
const city = user.address && user.address.city;
console.log(city); // null ← stopped at null, no crash

6. Optional Chaining ?. — Modern JavaScript ✨

Optional chaining ?. was added in ES2020. It is the modern, cleaner solution to the "safe property access" problem. Instead of writing user && user.address && user.address.city you just write user?.address?.city:

JavaScript — Optional Chaining ?.
// Without ?. — crashes if address is null
const user = { name: "Waheed", address: null };
// console.log(user.address.city); // ❌ TypeError: Cannot read properties of null

// Old fix — using && chains (messy)
const city1 = user && user.address && user.address.city;
console.log(city1); // null

// Modern fix — optional chaining ✅ (clean)
const city2 = user?.address?.city;
console.log(city2); // undefined ← no crash

// ?. with arrays
const arr = null;
console.log(arr?.[0]); // undefined ← no crash

// ?. with function calls
const obj = { greet: null };
console.log(obj.greet?.()); // undefined ← no crash

// Combine ?. with ?? for clean defaults
const profile = { user: null };
const name = profile?.user?.name ?? "Guest";
console.log(name); // "Guest" ← clean and safe ✅

// Real world — API response handling
const response = {
  data: {
    user: { name: "Waheed", city: "Faisalabad" }
  }
};
console.log(response?.data?.user?.name);    // "Waheed"
console.log(response?.data?.user?.salary);  // undefined ← no crash

7. Try It Yourself

Edit the code and click Run Code. Try changing the boolean values and watch how short circuit evaluation changes the results!

✏️ Try it Yourself — Logical Operators
OUTPUT
// Click Run Code to see output
💡 Edit the code and click Run!

8. Practice Tasks

Task 1 — Easy: Access Control

Create variables: isLoggedIn = true, isVerified = false, isPremium = true. Use logical operators to check: can the user access premium content (must be logged in AND verified AND premium)? Can they access basic content (logged in OR verified)? Log both results with descriptive messages.

Task 2 — Medium: Safe User Profile

Create a user object with name, address: null, and settings: { theme: "dark" }. Use optional chaining to safely access: user.address.city, user.settings.theme, user.social.twitter. Use ?? to provide fallback values for anything that returns undefined.

Task 3 — Hard: Dark Mode Toggle

Build a settings object with isDarkMode = false, fontSize = null, language = "". Write a function applySettings(settings) that: toggles dark mode using !, sets fontSize to 16 if null using ??=, sets language to "en" if empty using ||=. Use && to log "Dark mode enabled" only when isDarkMode is true after toggle. Log the final settings object.

Next Lesson
Day 11 — Conditional Statements: if, else, switch
View Full Roadmap →
Enjoying this roadmap?
Follow Muhammad Waheed Asghar for daily JavaScript tips and updates!

Popular Posts