CodeBlanks Logo Icon CodeBlanks

Logical operators

JavaScript course · Beginner · Lesson 10/133

Learn boolean logic and short-circuit evaluation with &&, || and !.

Logical operators

To combine several conditions you use logical operators. && means and: when both sides are true the result is true. || means or: when at least one side is true the result is true. ! means not: it flips true to false.

For a ticketed adult viewer: const allowed = hasTicket && age >= 18;. Both conditions must hold.

Short-circuit evaluation

Logical operators are lazy. With &&, if the left side is false, the right side is never checked because the result is already decided. This is called short-circuit. With ||, if the left side is true, the right side is skipped.

This is handy for defaults: const name = input || "Guest";. If input is empty, name becomes "Guest" automatically.

Exercise Compute the access check

hasTicket and isAdult are already declared. Declare a canEnter variable and assign it the result of hasTicket && isAdult.

Show example solution
const hasTicket = true;
const isAdult = true;
// Access check
let canEnter = hasTicket && isAdult;

Test yourself

  1. What is the result of true && false?

    console.log(true && false);
    • true
    • undefined
    • TypeError
    • false
    Show answer

    false — Correct. && returns true only when both sides are true; one false is enough.

  2. Write the NOT operator

    const isActive = false;
    const isPaused = ____isActive;
    console.log(isPaused);
    Show answer
    const isActive = false;
    const isPaused = !isActive;
    console.log(isPaused);
  3. Match the logical operator

    &&
    And
    ||
    Or
    !
    Not

All lessons in Beginner