Operators, Expressions & Precedence
Welcome to Lesson 5 of Phase 3: Operators & Input! An Operator is a special symbol used to perform calculations, compare values, assign variables, or evaluate logical decisions. In this masterclass chapter, we cover all 15 operator categories in JavaScript โ including strict equality (=== vs ==), short-circuit logical evaluation, modern ?? (Nullish Coalescing) & ?. (Optional Chaining), and Operator Precedence hierarchy.
| Operator | Name | Description | Code Example |
|---|---|---|---|
+ | Addition | Calculates sum of two numbers or concatenates strings. | 10 + 5 // 15 |
- | Subtraction | Calculates difference between two numbers. | 10 - 5 // 5 |
* | Multiplication | Multiplies two numeric values. | 10 * 5 // 50 |
/ | Division | Divides numerator by denominator. | 10 / 4 // 2.5 |
% | Modulus (Remainder) | Returns remainder after integer division. | 10 % 3 // 1 |
** | Exponentiation (Power) | Raises base to exponent power (ES2016). | 2 ** 3 // 8 |
Assignment operators assign values to variables with optional compound arithmetic shortcutting:
x = 10โ Simple Assignmentx += 5โ Compound Addition (equivalent tox = x + 5)x -= 3โ Compound Subtraction (equivalent tox = x - 3)x *= 2โ Compound Multiplication (equivalent tox = x * 2)x /= 4โ Compound Division (equivalent tox = x / 4)
JavaScript has two types of equality operators: Abstract Equality (==) and Strict Equality (===). Understanding this distinction is crucial to avoiding bugs!
Compares values AFTER performing implicit type coercion. String "5" == 5 evaluates to true!
Compares BOTH Data Type and Value without coercion. String "5" === 5 evaluates to false!
"use strict";
console.log('5' == 5); // true (Coerces string "5" to number 5)
console.log('5' === 5); // false (Different Data Types!)
console.log('5' != 5); // false
console.log('5' !== 5); // true (Strict Inequality)
console.log(null == undefined); // true
console.log(null === undefined); // false
- Logical AND (
&&): Returns the first Falsy value, or the last value if all are truthy. - Logical OR (
||): Returns the first Truthy value, or the last value if all are falsy. - Logical NOT (
!): Inverts the boolean truthiness of a value.!!valueconverts any value to its boolean equivalent.
"use strict";
let loggedInUser = "Ravi";
let displayName = loggedInUser || "Guest"; // Evaluates first truthy "Ravi"
console.log("Display Name:", displayName);
let emptyUser = "";
let fallbackName = emptyUser || "Guest User"; // Empty string is falsy -> "Guest User"
console.log("Fallback Name:", fallbackName);
let isMember = true;
let hasDiscount = isMember && "20% OFF"; // Evaluates second value if first is truthy
console.log("Discount:", hasDiscount);
ES2020 introduced two powerful operators to simplify null checks:
Returns right side ONLY if left side is null or undefined. Unlike ||, values like 0 or "" are NOT overwritten!
Safely accesses nested object properties without throwing TypeError if object reference is nullish.
"use strict";
// Nullish Coalescing (??) vs Logical OR (||)
let count = 0;
let val1 = count || 100; // 100 (because 0 is falsy for ||)
let val2 = count ?? 100; // 0 (because 0 is NOT nullish!)
console.log("val1 (OR):", val1, "| val2 (Nullish):", val2);
// Optional Chaining (?.)
const user = {
name: "Ravi",
profile: {
city: "Hyderabad"
}
};
console.log("City:", user?.profile?.city); // "Hyderabad"
console.log("ZipCode:", user?.address?.zipCode); // undefined (No TypeError crash!)
- Increment/Decrement:
++x(Pre-increment: adds 1 before evaluating) vsx++(Post-increment: adds 1 after returning current value). - Ternary Operator:
condition ? valueIfTrue : valueIfFalse(Inline shorthand for simple if-else). - Bitwise Operators:
&(AND),|(OR),^(XOR),~(NOT),<<(Left Shift),>>(Right Shift). Operations performed on 32-bit binary representation. - Operator Precedence Hierarchy: Grouping
()$ ightarrow$ Member Access.$ ightarrow$ Exponentiation**$ ightarrow$ Multiply/Divide* / %$ ightarrow$ Add/Subtract+ -$ ightarrow$ Comparison $ ightarrow$ Equality $ ightarrow$ Logical $ ightarrow$ Assignment.
Test ternary operators and strict equality logic:
"use strict";
let score = 85;
let result = score >= 50 ? "PASS โ
" : "FAIL โ";
console.log("Score:", score, "| Result:", result);
let inputVal = "100";
let targetVal = 100;
console.log("Strict Check (===):", inputVal === targetVal ? "Equal" : "Not Equal");