CodeBlanks Logo Icon CodeBlanks

Logical operators

Learn boolean logic with &&, || and !.

Logical operators

Logical operators combine boolean values: && (and), || (or), ! (not).

&& returns true if both conditions are true: age >= 18 && hasLicense. || returns true if at least one is true: isWeekend || isHoliday.

! inverts the value: !isActive. These operators are essential tools for combining conditions.

Short-circuit

Logical operators short-circuit: when the result is determined, they do not evaluate the other side.

For example, in false && something, since the left side is false, the result is definitely false; something is not evaluated. The same goes for true || something.

This is used for safe access: user && user.name. If user is null, the right side does not run; no error is thrown.

Practice Logical expression

Declare age = 20 and hasLicense = true. Compute canDrive as age >= 18 && hasLicense. Call console.log(canDrive).

Starter code

index.js
const age = 20;
const hasLicense = true;
// Compute canDrive as age >= 18 && hasLicense
// Log it with console.log

Sample solution

index.js
const age = 20;
const hasLicense = true;
const canDrive = age >= 18 && hasLicense;
console.log(canDrive);

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the && operator return?

  • Adds two numbers
  • Compares two values
  • Returns true if both conditions are true Correct answer
  • Returns true if one condition is true

Explanation: && returns true if both conditions are true.

2 Match the operators

Term Meaning
&& Logical and
|| Logical or
! Not
>= Greater or equal

3 && example

Question
const isValid = age >= 18 ____ hasLicense;
Answer
const isValid = age >= 18 && hasLicense;

Explanation: && requires both conditions to be true.

All lessons in Beginner