# Med Java

### Site Tools

java-script:bitwise-or-bitwise-and-ternary-optional-chaining-operators

# Java Script | Bitwise OR, ^ Bitwise XOR, & 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 XOR

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```

## & 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```
The bitwise operators work on integer values at the level of individual bits, and their behavior is entirely different from the logical operators ||, ??, and &&. While the logical operators evaluate values in a boolean context, the bitwise operators work directly with the binary representation of numbers.
Bitwise operations are typically used in lower-level programming tasks, such as manipulating flags and masks, whereas logical operators are used for flow control and combining conditions.

## ? 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```
This operator can be particularly helpful when dealing with objects that may or may not have certain properties or nested structures. 