- What are Operators in JavaScript?
Operators are symbols used to perform operations on values (called operands).
Example:
let result = 10 + 5;
Here:
-
10and5→ operands -
+→ operator
- Types of Operators (Basic Idea)
Some common operators:
- Arithmetic →
+,-,*,/ - Assignment →
=,+= - Comparison →
==,=== - Logical →
&&,||
Now we focus on Arithmetic operators (+ and -)
- Addition (
+) Operator
How it works:
- If both values are numbers → addition
- If any one is string → convert to string
- Then join (concatenate)
Examples
Number + Number
javascript
console.log(10 + 5); // 15
String + String
console.log("Hello" + " JS"); // "Hello JS"
String + Number
console.log("10" + 5); // "105"
Number + String
console.log(10 + "5"); // "105"
- Subtraction (
-) Operator
How it works:
- Convert both values to numbers
- Perform subtraction
- If not possible →
NaN
Examples
Number - Number
console.log(10 - 5); // 5
⚠️ String - Number
console.log("10" - 5); // 5
Number - String
console.log(10 - "5"); // 5
String - String
console.log("10" - "5"); // 5
Invalid String
console.log("Hello" - 5); // NaN
- Final Difference
| Operator | Behavior |
|---|---|
+ |
Can add OR join strings |
- |
Always numeric subtraction |
- Easy Memory Trick
console.log("5" + 5); // "55"
console.log("5" - 5); // 0
+ → string joins
- → number math only
Top comments (0)