04. Deep Dive into JavaScript Operators: Arithmetic, Assignment & Comparison
Introduction
Operators are the building blocks that let JavaScript perform calculations, assign values, compare data, and more. Understanding how different kinds of operators work is essential for writing functional, bug-free code. In this post, we explore:
- Arithmetic operators
- Assignment operators
- Comparison operators
- How they behave in JavaScript
1. Arithmetic Operators
Arithmetic operators let you perform mathematical operations. Here are the most common ones:
OperatorDescriptionExample+Addition5 + 3 results in 8-Subtraction10 - 4 results in 6*Multiplication7 * 2 results in 14/Division20 / 4 results in 5%Modulus (remainder)9 % 4 results in 1**Exponentiation2 ** 3 results in 8++Increment by 1x++ increases x by 1--Decrement by 1x-- decreases x by 1Examples:
Note on precedence:
Arithmetic operators follow order of operations (parentheses first, then exponents, then multiplication/division/modulus, then addition/subtraction). Use parentheses to control calculation order when needed.
2. Assignment Operators
Assignment operators combine operation and assignment in a compact form.
- = — basic assignment
- += — add and assign
- -= — subtract and assign
- *= — multiply and assign
- /= — divide and assign
- %= — modulus and assign
- **= — exponentiate and assign
Examples:
These operators make your code shorter and clearer.
3. Comparison Operators
Comparison operators evaluate relationships between values and return a boolean (true or false).
- == — equal to (does type coercion)
- === — strict equal (no type conversion)
- != — not equal (with type conversion)
- !== — strict not equal (no type conversion)
- > — greater than
- < — less than
- >= — greater than or equal
- <= — less than or equal
Examples:
Tip:
Prefer === and !== over == and != to avoid unexpected results due to automatic type conversion.
4. Combining Operators & Pitfalls
4.1 Operator Chaining
You can combine multiple operations in a single statement:
Use parentheses to control order and ensure clarity.
4.2 Implicit Type Conversion
When operators mix types (e.g., string and number), JavaScript may convert types implicitly:
This behavior may cause bugs, so be mindful of operand types. Using explicit conversion (Number(), String()) helps control outcomes.
4.3 NaN and Infinity
Some arithmetic operations can result in special values:
- 0 / 0 → NaN (Not a Number)
- Division by zero (nonzero / 0) → Infinity or -Infinity
- Operations involving NaN propagate NaN
Check with isNaN() to detect invalid results:
Conclusion
JavaScript’s operators allow you to perform math, assign values, and compare data. Mastering how they work—especially the nuances of assignment shorthand and comparison—lays a strong foundation for more advanced coding tasks.
04. Deep Dive into JavaScript Operators Arithmetic Assignment Comparison
coldshadow44 on 2025-10-12
(0)