Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Logical operators

Logical operators combine several conditions into one: "age is over 18 and there is a ticket", "it is a weekend or a holiday". The result is usually true or false, and it is used in an if.

AND — &&

The && operator gives true only when both parts are true:

console.log(true && false); // false

In practice there are comparisons on both sides:

const age = 20;
const hasTicket = true;
 
console.log(age >= 18 && hasTicket); // true

OR — ||

The || operator gives true when at least one part is true. The result is false only if both are false:

const day = 'Saturday';
 
console.log(day === 'Saturday' || day === 'Sunday'); // true

NOT — !

The ! operator flips a value: true becomes false and false becomes true. It goes in front of the value:

const isLoggedIn = false;
 
console.log(!isLoggedIn); // true

It helps to read ! as "not": !isLoggedIn means "not logged in".

Precedence

! runs first, then &&, and only then || — just as multiplication comes before addition. In complex conditions, add parentheses so the order is obvious:

const isAdmin = false;
const isOwner = true;
const isBlocked = false;
 
console.log((isAdmin || isOwner) && !isBlocked); // true

Default values

In fact || does not just return true or false but one of its own values: the first truthy one, or the last one. This is used to supply a fallback value:

const nickname = '';
 
console.log(nickname || 'Guest'); // Guest

The similar ?? operator returns the right side only when the left side is null or undefined. It treats zero and the empty string as normal values:

const count = 0;
 
console.log(count || 10); // 10
console.log(count ?? 10); // 0

If zero is a valid value — the number of items in a cart, for example — use ??.

Common mistake

You cannot compare a variable with several values at once by listing them with ||. The right side here is just a non-empty string, and it is always truthy:

const day = 'Monday';
 
console.log(day === 'Saturday' || 'Sunday'); // Sunday

Repeat the comparison for every value: day === 'Saturday' || day === 'Sunday'.

Thanks for reading!

Donate to the site — we work hard for you.