JavaScript Operators - Exercise 3
Multiplication is evaluated before addition unless parentheses change the order.
const result = 2 + 3 * 4;
console.log(result); // 14
console.log((2 + 3) * 4); // 20The nullish coalescing operator uses the fallback only for null or undefined, while OR also treats other falsy values as missing.
console.log(0 || 10); // 10
console.log(0 ?? 10); // 0Optional chaining stops property access when a value is nullish and returns undefined.
const user = {};
console.log(user.profile?.email); // undefined
// user.profile.email would throw a TypeErrorThe ** operator raises the left operand to the power of the right operand.
const square = 5 ** 2;
console.log(square); // 25??= assigns a fallback only when the existing value is null or undefined.
let timeout = 0;
timeout ??= 3000;
console.log(timeout); // 0Bitwise operators work on the binary representation of numbers and compare corresponding bits. Bitwise AND keeps a bit only when both inputs have it, while bitwise OR keeps it when either input has it.
console.log(5 & 3); // 1
console.log(5 | 3); // 7The logical NOT operator converts a value to a boolean and reverses its truthiness.
const isEmpty = "";
console.log(!isEmpty); // true
console.log(!(3 > 1)); // falseSeparating calculations makes precedence explicit and reduces mistakes caused by mixing side effects with other operators.
let total = 10;
const increase = 5;
total += increase;
console.log(total); // 15The conditional operator chooses one of two expressions based on whether a condition is truthy.
const age = 20;
const access = age >= 18 ? "allowed" : "denied";
console.log(access); // allowedThe && operator returns the first falsy operand, or the last operand when all values are truthy.
console.log("ready" && 42); // 42
console.log("" && 42); // ""