JavaScript Operators
JavaScript operators are special symbols used to perform operations on values and variables. These operations can range from simple arithmetic and assignment to comparison and logical evaluations.
Operators are categorized based on the type of operation they perform and the number of operands they take. An operand is the value or variable that the operator acts upon.
📊 Operator Categories
Arithmetic
Mathematical operations
+ - * / % **Assignment
Assign values
= += -= *= /=Comparison
Compare values
== === != !== > <Logical
Combine booleans
&& || ! ??Ternary
Conditional operator
? :Bitwise
Binary operations
& | ^ ~ << >>Type
Type checking
typeof instanceofOther
Miscellaneous
, void delete in➕ Arithmetic Operators
Mathematical Operations
Arithmetic operators perform mathematical calculations on numbers. JavaScript follows standard mathematical order of operations (PEMDAS).
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 10 - 4 | 6 |
* | Multiplication | 6 * 7 | 42 |
/ | Division | 15 / 3 | 5 |
% | Modulus | 17 % 5 | 2 |
** | Exponentiation | 2 ** 3 | 8 |
++ | Increment | x++ | x + 1 |
-- | Decrement | x-- | x - 1 |
🎯 Operator Precedence
JavaScript evaluates expressions in this order:
- Parentheses
() - Exponentiation
** - Multiplication/Division/Modulus
* / % - Addition/Subtraction
+ -
💡 String Concatenation
The + operator also concatenates strings. When one operand is a string, JavaScript converts the other to a string and concatenates them.
Try Arithmetic Operations:
🔄 Assignment Operators
Assigning Values
Assignment operators assign values to variables. Compound assignment operators perform an operation and assignment in one step.
| Operator | Example | Equivalent To | Description |
|---|---|---|---|
= | x = 5 | x = 5 | Simple assignment |
+= | x += 3 | x = x + 3 | Add and assign |
-= | x -= 2 | x = x - 2 | Subtract and assign |
*= | x *= 4 | x = x * 4 | Multiply and assign |
/= | x /= 2 | x = x / 2 | Divide and assign |
%= | x %= 3 | x = x % 3 | Modulus and assign |
**= | x **= 2 | x = x ** 2 | Exponentiate and assign |
⚠️ Chained Assignment
Multiple assignments like a = b = c = 5 are possible but can be confusing. The assignment is processed from right to left.
🎯 Destructuring Assignment (ES6)
Extract values from arrays or properties from objects into distinct variables.
const [a, b] = [1, 2];
const {x, y} = {x: 10, y: 20};⚖️ Comparison Operators
Comparing Values
Comparison operators compare two values and return a boolean (true or false). They're essential for conditional statements and loops.
| Operator | Name | Example | Description |
|---|---|---|---|
== | Equal to | 5 == '5' | True (type coercion) |
=== | Strict equal | 5 === '5' | False (different types) |
!= | Not equal | 5 != '6' | True |
!== | Strict not equal | 5 !== '5' | True |
> | Greater than | 10 > 5 | True |
< | Less than | 10 < 5 | False |
>= | Greater or equal | 10 >= 10 | True |
<= | Less or equal | 10 <= 5 | False |
🚫 Avoid Loose Equality
Always use === and !== instead of == and !=. Strict comparison prevents unexpected type coercion bugs.
🔍 Type Coercion Quirks
Loose equality can produce surprising results:
0 == false→ true'' == false→ truenull == undefined→ true'0' == false→ true
🔗 Logical Operators
Boolean Logic
Logical operators combine boolean values and return a boolean result. They're fundamental for conditional logic and flow control.
| Operator | Name | Example | Description |
|---|---|---|---|
&& | Logical AND | a && b | True if both are true |
|| | Logical OR | a || b | True if at least one is true |
! | Logical NOT | !a | True if operand is false |
?? | Nullish Coalescing | a ?? b | Returns b if a is null/undefined |
⚡ Short-circuit Evaluation
JavaScript stops evaluating logical expressions as soon as the result is determined. This is used for conditional execution and default values.
🎯 Truthy and Falsy Values
In logical operations, values are converted to booleans:
false0""nullundefinedNaN
- Everything else!
"hello"42[]true
❓ Ternary Operator
Conditional Operator
The ternary operator is a compact way to write simple if-else statements. It takes three operands and returns one of two values based on a condition.
| Syntax | Equivalent If-Else | Description |
|---|---|---|
condition ? expr1 : expr2 | if (condition) { expr1 } else { expr2 } | Returns expr1 if true, expr2 if false |
Best Practices:
- Use for simple, single-line conditions
- Avoid complex nested ternary operators
- Keep expressions simple and readable
- Use parentheses for complex conditions
💡 When to Use Ternary
Perfect for: variable assignments, return statements, and simple conditional rendering. Use if-else for complex logic with multiple statements.
🚫 Avoid This (Too Complex):
const result = a > b ? (c < d ? e : f) : (g > h ? i : j);Instead, use if-else for complex nested conditions.
🔢 Bitwise Operators
Binary Operations
Bitwise operators work on 32-bit binary representations of numbers. They're less common in web development but useful for performance optimization and low-level programming.
| Operator | Name | Example | Description |
|---|---|---|---|
& | AND | 5 & 3 | 1 (0101 & 0011 = 0001) |
| | OR | 5 | 3 | 7 (0101 | 0011 = 0111) |
^ | XOR | 5 ^ 3 | 6 (0101 ^ 0011 = 0110) |
~ | NOT | ~5 | -6 (~0101 = 1010) |
<< | Left shift | 5 << 1 | 10 (0101 << 1 = 1010) |
>> | Right shift | 5 >> 1 | 2 (0101 >> 1 = 0010) |
>>> | Zero-fill right shift | 5 >>> 1 | 2 (0101 >>> 1 = 0010) |
🎯 Practical Uses
Bitwise operators are great for: flags/permissions, color manipulation, cryptography, and performance-critical calculations.
💡 Common Bitwise Tricks
n & 1- Check if number is oddn & (n-1) === 0- Check if power of 2n << 1- Multiply by 2n >> 1- Divide by 2 (floor)a ^ b ^ b- Swap numbers
🔍 Type Operators
Type Checking
Type operators help determine the type of values, which is crucial in JavaScript's dynamically typed environment.
| Operator | Name | Example | Description |
|---|---|---|---|
typeof | Type of | typeof 42 | "number" |
instanceof | Instance of | arr instanceof Array | true |
typeof Return Values:
"undefined"- for undefined values"boolean"- for boolean values"number"- for numbers (including NaN)"string"- for strings"symbol"- for symbols (ES6)"function"- for functions"object"- for objects, arrays, and null
⚠️ typeof Quirks
typeof nullreturns"object"(historical bug)typeof NaNreturns"number"typeof []returns"object"- Use
Array.isArray()for array detection
🎯 instanceof Usage
Checks if an object is an instance of a constructor function. Works with built-in types (Array, Date, RegExp) and custom constructors.
🔧 Better Type Checking
function getType(value) {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
return typeof value;
}🎮 Practice: Build Utility Functions
Apply all the operators you've learned by implementing these utility functions. Each function uses different types of operators to solve common programming problems.
💪 Additional Challenges:
- Create a function that validates email format
- Build a simple calculator with all operations
- Create a password strength checker
- Implement a temperature converter
- Create a function that formats currency
- Build a random number generator with range
📚 Operator Summary
Key Takeaways:
- Use appropriate operators for different tasks
- Always prefer strict equality (
===/!==) - Understand operator precedence for complex expressions
- Use ternary operator for simple conditional assignments
Best Practices:
- Use parentheses to clarify complex expressions
- Avoid nested ternary operators for readability
- Use logical operators for default values and conditional execution
- Understand truthy/falsy values in logical operations
Now that you understand operators, you're ready to learn how to control the flow of your programs!
Next: Control Flow →📋 Operators Quick Reference
Arithmetic:
+ - * / % ** ++ --Assignment:
= += -= *= /= %= **=Comparison:
== === != !== > < >= <=Logical:
&& || ! ??Bitwise:
& | ^ ~ << >> >>>Other:
? : typeof instanceof