Logical & Nullish

AND, OR, NOT

Example

&& and || return one of their operands (not necessarily a boolean) and stop as soon as the result is known (short-circuit):

const age = 20, hasId = true;
console.log(age >= 18 && hasId);
console.log(!hasId);
console.log("" || "default");      // first truthy value
console.log("Asha" && "logged in"); // last value if all truthy
const user = null;
console.log(user && user.name);     // stops at null

Output

true
false
default
logged in
null

Nullish Coalescing (??)

Example

?? falls back only for null or undefined, while || also replaces 0 and "":

const qty = 0;
console.log(qty || 1);    // 1 (wrong: 0 is a valid quantity)
console.log(qty ?? 1);    // 0
let settings = { theme: undefined };
settings.theme ??= "light";   // assign only if null/undefined
console.log(settings.theme);

Output

1
0
light

Conditional (Ternary) Operator

Example

condition ? valueIfTrue : valueIfFalse:

const marks = 72;
const result = marks >= 40 ? "Pass" : "Fail";
console.log(result);
const grade = marks >= 90 ? "A" : marks >= 75 ? "B" : marks >= 60 ? "C" : "D";
console.log(grade);

Output

Pass
C