Operators+In JavaScript
Operators+In JavaScript
---
1. Arithmetic Operators
`+` (Addition)
`-` (Subtraction)
`*` (Multiplication)
`/` (Division)
`%` (Remainder/Modulus)
`**` (Exponentiation)
`++` (Increment)
`--` (Decrement)
Eg:
2. Assignment Operators
Assign values to variables:
`=` (Simple assignment)
`+=` (Add and assign)
`-=` (Subtract and assign)
`*=` (Multiply and assign)
`/=` (Divide and assign)
`%=` (Modulus and assign)
`**=` (Exponentiation and assign)
Eg:
let y = 5;
y **= 2; // y = 25
---
Eg:
4. Logical Operators
Used with boolean values:
`&&` (Logical AND)
`||` (Logical OR)
`!` (Logical NOT)
`??` (Nullish Coalescing)
Eg:
---
5. Bitwise Operators
`&` (AND)
`|` (OR)
`^` (XOR)
`~` (NOT)
`<<` (Left shift)
`>>` (Right shift)
`>>>` (Zero-fill right shift)
Eg:
---
6. String Operators
`+` (Concatenation)
`+=` (Concatenate and assign)
Eg:
---
Eg:
---
8. Unary Operators
Operate on a single operand:
`typeof` (Returns variable type)
`void` (Discards expression return value)
`delete` (Removes object properties)
`+` (Converts to number)
`-` (Negates a number)
Eg:
typeof 42; // "number"
---
9. Relational Operators
- `in` (Checks if property exists in an object)
- `instanceof` (Checks object type)
Eg:
---
Eg:
const arr = [...[1, 2], 3]; // [1, 2, 3]
-----------------------------------------------------------------------------------
--
Nullish Coalescing Operator (`??`) in JavaScript
-----------------------------------------------------------------------
The `??` operator (Nullish Coalescing) is a logical operator that returns its
right-hand operand when the left-hand operand is `null` or `undefined`. Otherwise,
it returns the left-hand operand.
Syntax:
leftOperand ?? rightOperand
---
Examples
1. Basic Usage
The `||` operator returns the right-hand operand for any falsy value (`0`, `""`,
`false`, `null`, `undefined`, `NaN`), while `??` only cares about `null` or
`undefined`.
let count = 0;
let defaultValue = 10;
Browser Support
- Supported in all modern browsers (Chrome, Firefox, Edge, Safari) and Node.js 14+.
- Not supported in Internet Explorer.
---
Summary:
`??` is ideal for providing fallbacks only when a value is `null` or `undefined`.
`||` is broader and replaces all falsy values, which may not always be desired.