ES6 - Operators
ES6 - Operators
Section titled “ES6 - Operators”An expression is a unit of code that evaluates to a value. Expressions are typically composed of:
- Operands: The data or values that the operator acts upon.
- Operator: A symbol or keyword that defines the operation to be performed on the operands.
For example, in the expression 5 + 10, 5 and 10 are operands, and + is the operator. JavaScript supports various types of operators.
1. Arithmetic Operators
Section titled “1. Arithmetic Operators”Perform mathematical calculations. Assume let a = 10; let b = 5;
| Operator | Description | Example | Result |
|---|---|---|---|
| + | Addition | a + b | 15 |
| - | Subtraction | a - b | 5 |
| * | Multiplication | a * b | 50 |
| / | Division | a / b | 2 |
| % | Modulus (Remainder) | a % b | 0 (10 divided by 5 has a remainder of 0) |
| ** | Exponentiation (ES2016) | a ** 2 (a to the power of 2) | 100 |
| ++ | Increment (adds 1) | let c = a++; (c is 10, a becomes 11) or let d = ++a; (a becomes 11, d is 11) | Varies |
| — | Decrement (subtracts 1) | let e = b--; (e is 5, b becomes 4) or let f = --b; (b becomes 4, f is 4) | Varies |
2. Relational (Comparison) Operators
Section titled “2. Relational (Comparison) Operators”Compare two values and return a Boolean value (true or false). Assume let x = 10; let y = 20; let z = '10';
| Operator | Description | Example | Result |
|---|---|---|---|
| > | Greater than | y > x | True |
| < | Less than | x < y | True |
| >= | Greater than or equal to | x >= 10 | True |
| <= | Less than or equal to | y <= 10 | False |
| == | Equality (Loose) | x == z (performs type coercion) | True (10 == ‘10’) |
| === | Strict Equality | x === z (no type coercion) | False (number 10 !== string ‘10’) |
| != | Inequality (Loose) | x != y | True |
| !== | Strict Inequality | x !== z | True |
Best Practice: Prefer strict equality (===) and strict inequality (!==) to avoid unexpected behavior due to type coercion.
3. Logical Operators
Section titled “3. Logical Operators”Combine or modify Boolean expressions. Assume let p = true; let q = false;
| Operator | Description | Example | Result |
|---|---|---|---|
| && | Logical AND | p && q | False (True if both operands are true) |
| || | Logical OR | p || q | True (True if at least one operand is true) |
| ! | Logical NOT | !p | False (Inverts the Boolean value) |
Logical operators often use short-circuiting. For example, in expr1 && expr2, if expr1 is false, expr2 is not evaluated.
4. Bitwise Operators
Section titled “4. Bitwise Operators”Perform operations on the binary representation of numbers. These are less commonly used in typical web development but are important in certain low-level programming scenarios.
| Operator | Name | Description |
|---|---|---|
| & | Bitwise AND | Returns a 1 in each bit position where both operands have a 1. |
| | | Bitwise OR | Returns a 1 in each bit position where at least one operand has a 1. |
| ^ | Bitwise XOR | Returns a 1 in each bit position where operands have different bits. |
| ~ | Bitwise NOT | Inverts all bits of its operand. |
| << | Left Shift | Shifts bits to the left, filling with zeros from the right. |
| >> | Sign-propagating Right Shift | Shifts bits to the right, preserving the sign bit. |
| >>> | Zero-fill Right Shift | Shifts bits to the right, filling with zeros from the left. |
Example: `5 & 1` (binary `0101 & 0001`) results in `1` (binary `0001`).5. Assignment Operators
Section titled “5. Assignment Operators”Assign values to variables. Often combined with other operators for shorthand.
| Operator | Example | Equivalent to |
|---|---|---|
| = | x = y | x = y (Simple assignment) |
| += | x += y | x = x + y (Add and assign) |
| -= | x -= y | x = x - y (Subtract and assign) |
| *= | x *= y | x = x * y (Multiply and assign) |
| /= | x /= y | x = x / y (Divide and assign) |
| %= | x %= y | x = x % y (Modulus and assign) |
| **= | x **= y | x = x ** y (Exponentiation and assign) |
Shorthand assignment also applies to bitwise operators (e.g., &=, |=).
6. Miscellaneous Operators
Section titled “6. Miscellaneous Operators”Conditional (Ternary) Operator (? :)
Section titled “Conditional (Ternary) Operator (? :)”A shorthand for an if-else statement. Syntax: condition ? exprIfTrue : exprIfFalse
let age = 20;let status = (age >= 18) ? 'Adult' : 'Minor';console.log(status); // Output: AdultString Concatenation Operator (+)
Section titled “String Concatenation Operator (+)”When used with strings, + concatenates them. If one operand is a string, the other is converted to a string.
let greeting = 'Hello, ' + 'World!';console.log(greeting); // Output: Hello, World!let message = 'Count: ' + 5;console.log(message); // Output: Count: 5Modern template literals (backticks `) are often preferred for string construction: let message = Count: ${5};
typeof Operator
Section titled “typeof Operator”Returns a string indicating the type of an unevaluated operand.
| Type | String Returned by typeof |
|---|---|
| Number | "number" |
| String | "string" |
| Boolean | "boolean" |
| Object (includes null, array, object literal) | "object" (Note: typeof null is an old bug, returns "object") |
| Function | "function" |
| Undefined variable or value | "undefined" |
| Symbol (ES6) | "symbol" |
| BigInt (ES2020) | "bigint" |
console.log(typeof 42); // "number"console.log(typeof 'hello'); // "string"console.log(typeof undefined); // "undefined"instanceof Operator
Section titled “instanceof Operator”Checks if an object is an instance of a particular constructor or class. object instanceof Constructor
let arr = [1, 2, 3];console.log(arr instanceof Array); // trueconsole.log(arr instanceof Object); // true (Arrays are objects)
class Person {}let p = new Person();console.log(p instanceof Person); // trueComma Operator (,)
Section titled “Comma Operator (,)”Evaluates multiple expressions from left to right and returns the value of the last expression. Used rarely, sometimes in for loops.
let x = (1, 2, 3);console.log(x); // Output: 3Spread (...) and Rest (...) Operators (ES6)
Section titled “Spread (...) and Rest (...) Operators (ES6)”Spread Operator: Expands an iterable (like an array or string) into individual elements, or an object into key-value pairs. Useful for copying arrays/objects, merging them, or passing array elements as function arguments.
const arr1 = [1, 2];const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]const obj1 = { a: 1, b: 2 };const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }Rest Parameter: Collects multiple function arguments into a single array. Must be the last parameter in a function definition.
function sum(...numbers) { return numbers.reduce((acc, current) => acc + current, 0);}console.log(sum(1, 2, 3, 4)); // Output: 10Nullish Coalescing Operator (??) (ES2020)
Section titled “Nullish Coalescing Operator (??) (ES2020)”Returns its right-hand side operand when its left-hand side operand is null or undefined, otherwise returns its left-hand side operand. It’s a way to provide default values for potentially nullish variables.
const foo = null ?? 'default string'; // foo is 'default string'const bar = 0 ?? 42; // bar is 0 (0 is not null or undefined)Optional Chaining (?.) (ES2020)
Section titled “Optional Chaining (?.) (ES2020)”Allows reading the value of a property located deep within a chain of connected objects without having to explicitly validate that each reference in the chain is valid. If a reference is null or undefined, the expression short-circuits and evaluates to undefined instead of throwing an error.
const adventurer = { name: 'Alice', cat: { name: 'Dinah' }};
const dogName = adventurer.dog?.name;console.log(dogName); // undefined (adventurer.dog is undefined, no error)
const catName = adventurer.cat?.name;console.log(catName); // Dinah