JS Fundamentals
Operators
Master JavaScript operators. Understand arithmetic, comparison, logical, assignment, bitwise, and conditional operators, along with precedence and associativity.
1. Introduction
Operators are built-in mathematical and logical utilities used to assign, compare, calculate, and transform variables. JavaScript supports a wide range of operators, from basic arithmetic to advanced bitwise and logical operations.
2. Why It Matters
Understanding operator precedence and short-circuit evaluation prevents calculation errors and lets you write concise, bug-free conditional statements.
3. Real-World Analogy
Think of an Assembly Line:
- Arithmetic Operators (Workers): Assemble or modify packages (adding components, cutting materials).
- Comparison Operators (Inspectors): Check if packages match height or weight requirements (equal, heavier).
- Logical Operators (Quality Gateways): Direct packages based on rules. For example, "if label is correct AND weight is good, ship it; otherwise, reject it."
4. How It Works
Operators are categorized by their action:
1. Arithmetic Operators:
+ (addition), - (subtraction), (multiplication), / (division), % (remainder), * (exponentiation).
2. Logical Operators (with Short-Circuiting):
&&(Logical AND): Returns the first falsy operand, or the last operand if all are truthy.||(Logical OR): Returns the first truthy operand, or the last operand if all are falsy.!(Logical NOT): Inverts boolean state.
3. Bitwise Operators:
Perform operations on 32-bit binary representations of numbers: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (sign-propagating right shift).
5. Internal Architecture
Operator execution is governed by Precedence (order of execution) and Associativity (direction of evaluation when operators have the same precedence). For example, multiplication (*) has higher precedence than addition (+).
6. Syntax & Precedence
Precedence levels for common operators (highest to lowest):
- Grouping:
( ... ) - Member Access / Call:
obj.prop,fn() - Increment/Decrement:
++,-- - Arithmetic:
**, then* / %, then+ - - Comparison:
< <= > >=, then== === !== - Logical:
&&, then|| - Assignment:
= += -=
7. Practical Example
Here is an example showing the use of assignment and logical operators:
8. Common Mistakes
- Overusing short-circuiting with falsy values: Using
||for default values fails when the provided value is a valid falsy value, like0or"". Use the nullish coalescing operator (??) instead.
9. Quick Quiz
Q1: What does console.log('hello' && 0 || true) output?
A) "hello"
B) true
Answer: B — 'hello' && 0 short-circuits and evaluates to 0 because 0 is falsy. Then 0 || true evaluates to true.
10. Scenario-Based Challenge
The Multi-Flag Check:
An admin portal triggers user actions under these rules: the user must have the isAdmin flag set, OR they must be isModerator AND have writeAccess. Write the optimal conditional statement using logical operators to enforce these permission rules.
11. Debugging Exercise
Fix the order of operations in the calculation below:
const basePrice = 100;
const taxRate = 0.15;
// Objective: Apply tax on price, then deduct a 20 dollar coupon
const finalPrice = basePrice * 1 + taxRate - 20; // buggy formula
View Solution
Diagnosis: The multiplication runs first: basePrice * 1, then adds taxRate, and subtracts 20. This is mathematically incorrect because the tax was not applied to the base price.
Fix: Use grouping parentheses to calculate the tax correctly:
const finalPrice = (basePrice * (1 + taxRate)) - 20; // 95
12. Interview Questions
🟢 Q1: Explain how short-circuit evaluation works in logical operators.
Answer: In JavaScript, logical operators evaluate from left to right.
• For &&, if the first operand is falsy, the engine short-circuits and returns it immediately without evaluating the second operand.
• For ||, if the first operand is truthy, the engine short-circuits and returns it immediately.
13. Production Considerations
- • Use Nullish Coalescing (??): When building configurations, use
??instead of||for setting defaults, ensuring numbers like0or booleans likefalseare handled correctly.