JavaScript Operators
JavaScript Operators
1. What Are Operators? 🤔
An operator is a symbol that tells the program to perform an operation on values.
Example:
let result = 5 + 3;
Here:
5 and 3 → operands
+ → operator
The + operator adds the numbers together.
Output:
8
2. Arithmetic Operators ➕➖✖️➗
Arithmetic operators perform basic mathematical calculations.
| Operator | Meaning | Example |
|---|---|---|
| + | Addition | 5 + 3 |
| - | Subtraction | 10 - 4 |
| * | Multiplication | 3 * 4 |
| / | Division | 12 / 3 |
| % | Modulus (remainder) | 10 % 3 |
Example in JavaScript
let a = 10;
let b = 3;
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
console.log(a % b);
Output:
13
7
30
3.333...
1
Explanation:
10 % 3 = 1
Because 3 goes into 10 three times with remainder 1.
3. Comparison Operators 🔍
Comparison operators compare two values and return true or false.
| Operator | Meaning | Example |
|---|---|---|
| == | Equal value | 5 == "5" |
| === | Equal value and type | 5 === "5" |
| != | Not equal | 5 != 3 |
| > | Greater than | 10 > 5 |
| < | Less than | 4 < 8 |
Example
console.log(5 == "5");
console.log(5 === "5");
Output:
true
false
Why?
5 == "5" → only compares values
5 === "5" → compares value AND type
So:
5 == "5" → true
5 === "5" → false
Because "5" is a string, not a number.
4. Logical Operators 🔗
Logical operators combine multiple conditions.
| Operator | Meaning |
|---|---|
| && | AND |
| ! | NOT |
AND Operator (&&)
Returns true only if both conditions are true.
let age = 20;
console.log(age > 18 && age < 30);
Output:
true
Because both conditions are true.
OR Operator (||)
Returns true if at least one condition is true.
console.log(5 > 10 || 8 > 3);
Output:
true
Because 8 > 3 is true.
NOT Operator (!)
Reverses a boolean value.
console.log(!true);
console.log(!false);
Output:
false
true
Logical Operator Truth Table
5. Assignment Operators 📝
Assignment operators assign values to variables.
| Operator | Example | Meaning |
|---|---|---|
| = | x = 5 | Assign value |
| += | x += 3 | x = x + 3 |
| -= | x -= 2 | x = x - 2 |
Example
let x = 10;
x += 5;
console.log(x);
Output:
15
Explanation:
x += 5
means
x = x + 5
Operator Categories Diagram
Assignment Practice 💻
Try these exercises.
1. Perform Arithmetic Operations
let a = 12;
let b = 4;
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
2. Compare Two Values
let x = 5;
let y = "5";
console.log(x == y);
console.log(x === y);
Observe the difference in output.
3. Use Logical Operators
let age = 22;
if (age > 18 && age < 60) {
console.log("You are eligible to work");
}