This is an old revision of the document!
Table of Contents
Java Script | Bitwise OR, & Bitwise AND, ? Ternary Conditional Operator and ?. Optional Chaining Operator
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.
| (Bitwise OR)
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
& (Bitwise AND)
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
? (Ternary Conditional Operator)
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'
?. (Optional Chaining Operator)
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