Logical Operators

Combine conditions with AND, OR and NOT.

Syntaxa && b a || b !a

Logical operators combine or invert Boolean values.

  • && (AND) — true only if both sides are true.
  • || (OR) — true if at least one side is true.
  • ! (NOT) — inverts true to false and vice versa.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Gate access to an admin route by checking both isLoggedIn && isAdmin before rendering the page.
  • Show a fallback username with || when the user's display name is an empty string.
  • Exclude a condition using ! to show a "No results found" message when a search returns nothing.

More examples

AND gate for permissions

Uses && so both conditions must be true to allow admin access.

Example · js
const isLoggedIn = true;
const isAdmin = false;
if (isLoggedIn && isAdmin) {
  console.log("Welcome, admin");
} else {
  console.log("Access denied");
}

OR fallback for display name

Uses || to fall back to "Anonymous" when the display name is an empty (falsy) string.

Example · js
const profile = { displayName: "" };
const name = profile.displayName || "Anonymous";
console.log(name); // "Anonymous" – empty string is falsy

NOT to invert a condition

Applies ! to invert the length check, entering the block when the results array is empty.

Example · js
const results = [];
if (!results.length) {
  console.log("No results found.");
}

Discussion

  • Be the first to comment on this lesson.