Operators are symbols used to execute certian operations represented by it.
🧮 Arithmetic operators
Consider y = 5
| Operator | Example | Result | Description |
|---|---|---|---|
| + | x = y + 2 | 7 | Addition |
| - | x = y - 2 | 3 | Subtraction |
| * | x = y * 2 | 10 | Multiplication |
| / | x = y / 2 | 2.5 | Division |
| % | x = y % 2 | 1 | Remainder (Modulo) |
| ** | x = y ** 2 | 25 | Exponentiation |
| ++ | x = ++y | 6 | Pre-increment |
| -- | x = --y | 4 | Pre-decrement |
🟰 Assignment operators
Consider x = 10 y = 5
| Operator | Example | Result | Description |
|---|---|---|---|
| = | x = y | 5 | |
| += | x += y | 15 | x=x+y |
| -= | x -= y | 5 | x=x-y |
| *= | x *= y | 50 | x=x*y |
| /= | x /= y | 2 | x=x/y |
| %= | x %= y | 0 | x=x%y |
| ** | x **= y | 100000 | x = x ** y |
➕ operator logic
The + operator performs either addition or string concatenation.
- If string concatenation is triggered, values are converted to strings.
- Otherwise, values are converted to primitives, then numeric addition is performed.
- Objects and arrays are converted to primitive values when necessary.
txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2; // What a very nice day
With mixed data types, the + operator causes JavaScript to run through a set sequence of type conversions
IF String is present -> Convert into String and concatenate
IF NOT
IF Object/Array is present -> Convert into primitive
If NOT
Convert into Numeric type and add
If NOT possible to even convert into number
return NaN
Illustraction of + operator
[] + 1 // "1"
"Hi" + 1 // "Hi1"
true + false // 1
true + "1" // "true1"
true + 1 // 2
null + 1 // 1
undefined + 1 // NaN
Note
Other arithmetic operators try to convert all other types into numeric.
Ex: "5" - 5 --> 0
⚖️Comparison operators
| Operator | Description | Example | Result |
|---|---|---|---|
| == | equal to | true == 1 | true |
| === | exactly equal to | true === 1 | false |
| != | not equal to | true != 1 | false |
| !== | Strictly not equal to | true !== 1 | true |
| < | Less than | 1 < 3 | true |
| > | Greater than | 4 > 5 | false |
| <= | Less than or equal to | 1 <= 1 | true |
| >= | Greater than or equal to | 10 >= 20 | false |
🧠 Logical operators
| Operator | Description | Example |
|---|---|---|
| AND && | True if all conditions are true | (x == 3)&&(y > 0) |
| OR || | True if any one of all conditions is true | (x == 3)||(y > 0) |
| NOT ! | Toggles the condition result | !(x == 3) |
Note
Logical operators can return actual values, not just
trueorfalse."Hello" && 5 // 5 "" || "Hi" // "Hi" !0 // true
❓Conditional operator
Syntax:
variable = condition ? value_if_true : value_if_false
Example
isAdult = (age >= 18) ? "Yes" : "No" ;
Comments
Join the discussionNo comments yet. Be the first to comment.
Decode Javascript
Explore JavaScript one concept at a time, from the fundamentals to advanced topics. Learn through clear explanations, practical examples, and code as we uncover how JavaScript works and use it to build for the web.
