Real-Life Example of Operators
Think of operators as tools in a toolbox. For instance, if you want to cut a piece of wood (a task), you use a saw (an operator). In JavaScript, operators allow us to perform tasks like calculations, comparisons, and logical operations on values.
Operator
In JavaScript, an operator is a special symbol used to perform operations on values and variables. Operators allow you to manipulate data, compare values, perform arithmetic calculations, assign values, and control program flow. They are categorized into different types, such as arithmetic, comparison, logical, bitwise, assignment, and ternary operators.
Let's discuss each type of operator one by one.
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, etc.
Let's understand with table and code :Table
| Operator | Description | Example | Result |
|---|---|---|---|
| + | Addition | 5 + 3 | 8 |
| - | Subtraction | 5 - 3 | 2 |
| * | Multiplication | 5 * 3 | 15 |
| / | Division | 10 / 2 | 5 |
| % | Modulus (Remainder) | 10 % 3 | 1 |
| ** | Exponentiation | 2 ** 3 | 8 |
| ++ | Increment | let a = 5; a++ | 6 |
| -- | Decrement | let a = 5; a-- | 4 |
// Examples of Arithmetic Operators
const a = 10;
const b = 5;
console.log(a + b); // Addition: 10 + 5 = 15
console.log(a - b); // Subtraction: 10 - 5 = 5
console.log(a * b); // Multiplication: 10 * 5 = 50
console.log(a / b); // Division: 10 / 5 = 2
console.log(a % b); // Modulus (Remainder): 10 % 5 = 0
console.log(a ** 2); // Exponentiation: 10^2 = 100
// Increment and Decrement
let x = 5;
console.log(++x); // Pre-increment: 6
console.log(x++); // Post-increment: 6 (then x becomes 7)
console.log(--x); // Pre-decrement: 6
console.log(x--); // Post-decrement: 6 (then x becomes 5)
2. Assignment Operators
Assignment operators assign values to variables.
Let's understand with table and code :Table
| Operator | Description | Example |
|---|---|---|
| = | Assign value | x = 10 |
| += | Add and assign | x += 5 // x = x + 5 |
| -= | Subtract and assign | x -= 5 // x = x - 5 |
| *= | Multiply and assign | x *= 5 // x = x * 5 |
| /= | Divide and assign | x /= 5 // x = x / 5 |
| %= | Modulus and assign | x %= 3 // x = x % 3 |
| **= | Exponentiation and assign | x **= 2 // x = x ** 2 |
// Examples of Assignment Operators
let x = 10; // Assign value
console.log(x); // Output: 10
x += 5; // Add and assign (x = x + 5)
console.log(x); // Output: 15
x -= 3; // Subtract and assign (x = x - 3)
console.log(x); // Output: 12
x *= 2; // Multiply and assign (x = x * 2)
console.log(x); // Output: 24
x /= 4; // Divide and assign (x = x / 4)
console.log(x); // Output: 6
x %= 5; // Modulus and assign (x = x % 5)
console.log(x); // Output: 1
x **= 2; // Exponentiation and assign (x = x ** 2)
console.log(x); // Output: 13. Comparison Operators
Comparison operators compare two values and return a boolean (true/false).
Let's understand with table and code :Table
| Operator | Description | Example |
|---|---|---|
| == | Equal to (loose) | 5 == "5" // true |
| === | Equal to (strict) | 5 === "5" // false |
| != | Not equal to (loose) | 5 != "5" // false |
| !== | Not equal to (strict) | 5 !== "5" // true |
| > | Greater than | 10 > 5 // true |
| < | Less than | 10 < 5 // false |
| >= | Greater than or equal to | 10 >= 10 // true |
| <= | Less than or equal to | 10 <= 5 // false |
// Comparison Operators Examples
console.log(5 == "5"); // true (loose equality)
console.log(5 === "5"); // false (strict equality)
console.log(5 != "5"); // false (loose inequality)
console.log(5 !== "5"); // true (strict inequality)
console.log(10 > 5); // true (greater than)
console.log(10 < 5); // false (less than)
console.log(10 >= 10); // true (greater than or equal)
console.log(10 <= 5); // false (less than or equal)4. Logical Operators
Logical operators in JavaScript are used to perform operations on boolean values or expressions. They help in decision-making by combining multiple conditions or inverting a boolean value.
Types of Logical Operators:&&(AND) – Returns the first falsy value (short-circuits), or the last truthy value if all are truthy.||(OR) – Returns the first truthy value (short-circuits), or the last falsy value if all are falsy.!(NOT) – Inverts the boolean value (i.e.,truebecomesfalseand vice versa).
Short-circuiting means that JavaScript stops evaluating an expression as soon as the result is determined.
// Logical AND (&&) - Stops at the first falsy value, otherwise returns the last truthy
console.log(true && false); // Output: false (short-circuits at false)
console.log(1 && 2 && 3); // Output: 3 (all truthy, returns the last one)
console.log(0 && 5); // Output: 0 (first falsy, stops evaluation)
// Logical OR (||) - Stops at the first truthy value, otherwise returns the last falsy
console.log(true || false); // Output: true (short-circuits at true)
console.log(0 || "" || null || "Hello" || 42); // Output: "Hello" (first truthy)
console.log(0 || "" || null); // Output: null (all falsy, returns last one)
// Logical NOT (!) - Inverts the boolean value
console.log(!true); // Output: false
console.log(!0); // Output: true (0 is falsy, so NOT makes it true)
These operators are commonly used in if conditions, loops, and expressions to control the program flow efficiently.
5. Ternary Operator
The ternary operator (condition ? expression1 : expression2) is a shorthand for anif-else statement. It evaluates a condition and returns one of two values based on whether the condition is true or false.
// Basic syntax:
condition ? value_if_true : value_if_false;Example 1: Checking Agelet age = 18;
let status = age >= 18 ? 'Adult' : 'Minor';
console.log(status); // Output: 'Adult'Example 2: Even or Odd Numberlet number = 7;
let result = number % 2 === 0 ? "Even" : "Odd";
console.log(result); // Output: "Odd"Example 3: Nested Ternary OperatorTernary operators can also be nested, but be careful as it may reduce readability.
let score = 85;
let grade = score >= 90 ? 'A' :
score >= 80 ? 'B' :
score >= 70 ? 'C' : 'F';
console.log(grade); // Output: 'B'Example 4: Using Ternary for Short-CircuitingThe ternary operator can be used instead of logical short-circuiting.
Logical Short-Circuiting
// Using Logical Short-Circuiting (&& and ||)
let isLoggedIn = true;
let messageShort = isLoggedIn && "Welcome back!" || "Please log in";
console.log(messageShort); // Output: "Welcome back!"
Using Ternary Operatorlet isLoggedIn = true;
let message = isLoggedIn ? "Welcome back!" : "Please log in";
console.log(message); // Output: "Welcome back!"🌟 When to Use the Ternary Operator?- When you need a concise and readable conditional expression.
- When there are only two possible outcomes (true/false, yes/no, etc.).
- When simplifying simple if-else conditions in assignments.
- When conditions are complex or require multiple statements.
- When readability is reduced due to too many nested ternary operators.
- When the condition needs side effects (e.g., multiple operations).
While the ternary operator is powerful, overusing it in complex scenarios can make code harder to read. Always consider readability and maintainability!
6. Bitwise Operators
Bitwise operators perform operations on the binary representations of numbers. These operators treat numbers as a sequence of 32 bits (0s and 1s) at the binary level.
Types of Bitwise Operators:&(AND) – Performs bitwise AND.|(OR) – Performs bitwise OR.^(XOR) – Performs bitwise XOR (exclusive OR).~(NOT) – Inverts bits (bitwise NOT).<<(Left Shift) – Shifts bits to the left.>>(Right Shift) – Shifts bits to the right.
// Examples of Bitwise Operators
// Bitwise AND (&) - Both bits must be 1 to return 1
console.log(5 & 1); // Output: 1
// (Binary: 5 = 101, 1 = 001 → 101 & 001 = 001)
// Bitwise OR (|) - At least one bit must be 1 to return 1
console.log(5 | 1); // Output: 5
// (Binary: 5 = 101, 1 = 001 → 101 | 001 = 101)
// Bitwise XOR (^) - Returns 1 if bits are different, otherwise 0
console.log(5 ^ 1); // Output: 4
// (Binary: 5 = 101, 1 = 001 → 101 ^ 001 = 100)
// Bitwise NOT (~) - Inverts bits (flips 0s and 1s, then adds 1)
console.log(~5); // Output: -6
// (Binary: 5 = 00000000000000000000000000000101 → ~5 = 11111111111111111111111111111010 (-6 in two's complement))
// Left Shift (<<) - Shifts bits to the left, multiplying by 2^n
console.log(5 << 1); // Output: 10
// (Binary: 5 = 101 → 1010 (10))
// Right Shift (>>) - Shifts bits to the right, dividing by 2^n
console.log(5 >> 1); // Output: 2
// (Binary: 5 = 101 → 10 (2))
🛠 Practical Use Cases:- Bitwise operations are faster for some arithmetic operations.
- Efficient way to store multiple boolean values in a single integer.
- Used in low-level programming, encryption, and network protocols.
- Graphics programming (shifting bits for image processing).
Though bitwise operators are not commonly used in everyday JavaScript, understanding them helps when working with binary calculations, permissions handling, and performance optimization in certain cases.
7. typeof Operator
The typeof operator is used to determine the type of a variable.
// Examples of typeof Operator
console.log(typeof 42); // Output: "number"
console.log(typeof 'Hello'); // Output: "string"
console.log(typeof true); // Output: "boolean"
console.log(typeof undefined); // Output: "undefined"
console.log(typeof {}); // Output: "object"8. ?? Nullish Coalescing Operator
The ?? operator returns the right-hand value only if the left-hand value is null or undefined. It's useful for providing default values without treating false, 0, or '' as missing.
// Examples of ?? (Nullish Coalescing)
const name = null ?? "Guest";
console.log(name); // Output: "Guest"
const age = 0 ?? 18;
console.log(age); // Output: 0 (not null or undefined)
const user = undefined ?? "Anonymous";
console.log(user); // Output: "Anonymous"
const emptyString = "" ?? "Default";
console.log(emptyString); // Output: "" (not null or undefined)