Operators (Arithmetic, Comparison, Logical, Ternary)
Operators let you perform calculations, make logical comparisons, and control application decisions.
What is it?
Operators are special symbols used to perform operations on operands (values and variables).
Why is it used?
Used for cart discounts, scoring algorithms, form validations, and conditional logic.
Detailed Explanation
Operator Categories:
• Arithmetic: `+`, `-`, `*`, `/`, `%` (modulo/remainder), `**` (exponentiation).
• Comparison: Strict Equality `===` (checks value AND type), Loose Equality `==` (coerces types—avoid!), Strict Inequality `!==`, `>`, `<`, `>=`, `<=`.
• Logical: `&&` (AND), `||` (OR), `!` (NOT), `??` (Nullish Coalescing—returns right side only if left is null/undefined).
• Ternary Operator: `condition ? valueIfTrue : valueIfFalse` (compact if-else expression).
Syntax Structure
Syntax Blueprint
let total = 10 + 5 * 2;
let isAdult = age >= 18;
let status = score >= 50 ? "Pass" : "Fail";
Code Example
JAVASCRIPT Code
// Course Discount Calculator
const coursePrice = 2500;
const bundlePrice = 5397;
const numberOfCourses = 3;
// Calculate savings
const individualTotal = coursePrice * numberOfCourses; // 7500
const savings = individualTotal - bundlePrice; // 2103
const discountPercent = Math.round((savings / individualTotal) * 100); // 28%
// Strict Comparison
const hasDiscount = savings > 0;
// Ternary Expression
const badgeText = hasDiscount ? `Save ₹${savings} (${discountPercent}% OFF)` : "Regular Price";
console.log("Individual:", individualTotal);
console.log("Bundle:", bundlePrice);
console.log("Savings:", savings);
console.log("Badge:", badgeText);
// Strict vs Loose Equality Warning
console.log("5 == '5' :", 5 == '5'); // true (Dangerous type coercion!)
console.log("5 === '5':", 5 === '5'); // false (Safe strict equality)
Explanation of the Code
• Calculates total savings using arithmetic operators.
• Demonstrates the ternary operator to generate promo badges dynamically.
• Highlights why you should always use `===` instead of `==`.
Expected Output
Individual: 7500
Bundle: 5397
Savings: 2103
Badge: Save ₹2103 (28% OFF)
5 == '5' : true
5 === '5': false
Real-World Application
Used across e-commerce checkouts for coupon codes, tax calculations, and shipping fee evaluations.
Common Mistakes to Avoid
• Using loose equality `==` which leads to notorious bugs due to implicit type coercion.
• Confusing assignment `=` with strict comparison `===`.
Quick Practice Challenge
Write a ternary expression that checks if a student's attendance is 75% or higher and returns 'Eligible for Exam' or 'Shortage'.
Key Takeaways
• Always use `===` and `!==` for strict value and type equality.
• The ternary operator `condition ? a : b` provides clean inline branching.
• Use `??` (nullish coalescing) when assigning default fallback values.