In JavaScript, there are the | (bitwise OR) and & (bitwise AND) operators, which are different from || and &&. These operators perform bitwise operations, which means they operate on the binary representations of numbers.
The | operator returns a value where each bit is set if the corresponding bit is set in either of the two operands:
const a = 5; // binary: 101 const b = 3; // binary: 011 const result = a | b; // binary: 111, decimal: 7
The ^ XOR (exclusive or) operation returns true if exactly one of the bits being compared is true:
let a = 5; // binary: 0101 let b = 3; // binary: 0011 let result = a ^ b; // binary: 0110, decimal: 6
The & operator returns a value where each bit is set if the corresponding bit is set in both operands:
const a = 5; // binary: 101 const b = 3; // binary: 011 const result = a & b; // binary: 001, decimal: 1
The ternary conditional operator is a concise way to perform a conditional (if-else-like) operation.
Its syntax is:
condition ? expressionIfTrue : expressionIfFalse
Example:
const age = 18; const status = age >= 21 ? 'adult' : 'minor'; console.log(status); // Output: 'minor'
Introduced in ECMAScript 2020, the optional chaining operator ?. allows you to access properties of objects without having to check if the object or property exists. If the object or property doesn't exist, the expression short-circuits and returns undefined.
Example:
const user = { name: 'John', address: { city: 'New York' } }; const city = user?.address?.city; // 'New York' const zip = user?.address?.zip; // undefined