Lesson goal: Calculate values, compare them, and combine true-or-false conditions.
An operator is a symbol that performs an operation on values.
| Operator | Purpose | Example | Result |
|---|---|---|---|
+ |
Addition | 10 + 3 |
13 |
- |
Subtraction | 10 - 3 |
7 |
* |
Multiplication | 10 * 3 |
30 |
/ |
Division | 10 / 2 |
5 |
% |
Remainder | 10 % 3 |
1 |
** |
Exponentiation | 2 ** 3 |
8 |
% gives the remainder after division. It is not a percentage operator.
Calculate the cost of notebooks
const notebookPrice = 60;
const notebookQuantity = 3;
const notebookTotal = notebookPrice * notebookQuantity;
console.log(notebookTotal);
180
console.log(10 + 5 * 2);
console.log((10 + 5) * 2);
20
30
Update a number
let quantity = 2;
quantity += 1;
console.log(quantity);
3
quantity += 1 is a shorter form of:
quantity = quantity + 1;
-=, *=, and /=.Comparison operators
Comparisons produce true or false.
| Operator | Meaning | Example | Result |
|---|---|---|---|
=== |
Strictly equal | 60 === 60 |
true |
!== |
Not strictly equal | 60 !== 50 |
true |
> |
Greater than | 60 > 50 |
true |
< |
Less than | 60 < 50 |
false |
>= |
Greater than or equal | 60 >= 60 |
true |
<= |
Less than or equal | 50 <= 60 |
true |
Assignment and comparison are different
const price = 60;
console.log(price === 60);
= assigns the value. === compares it.
Strict equality also checks type:
console.log(60 === "60");
false
60 and the string "60" have different types.JavaScript also has ==, which can convert types during comparison. We will use === and !== by default to make comparisons easier to understand.
Check whether payment is enough
const billTotal = 180;
const amountPaid = 200;
console.log(amountPaid >= billTotal);
true
For boolean conditions:
| Operator | Meaning | Example |
|---|---|---|
&& |
AND: both conditions must be true | true && false → false |
|| |
OR: at least one condition must be true | true || false → true |
! |
NOT: reverses the boolean value | !true → false |
Example:
const isEnrolled = true;
const hasCompletedLesson = false;
console.log(isEnrolled && hasCompletedLesson);
console.log(isEnrolled || hasCompletedLesson);
console.log(!hasCompletedLesson);
false
true
true
&& and || can return non-boolean values. Here, we are using them with boolean conditions.Combine comparisons
const notebookQuantity = 3;
const isWithinOrderLimit =
notebookQuantity >= 1 && notebookQuantity <= 10;
console.log(isWithinOrderLimit);
true
A note about decimals
Some decimal calculations are not represented exactly:
console.log(0.1 + 0.2);
0.30000000000000004
A student buys four pens at ₹15 each and pays ₹100.
Calculate:
Solution:
const penPrice = 15;
const penQuantity = 4;
const amountPaid = 100;
const totalCost = penPrice * penQuantity;
const change = amountPaid - totalCost;
console.log(totalCost);
console.log(change);
console.log(amountPaid >= totalCost);
60
40
true
Arithmetic operators calculate values. Comparison operators compare them. Logical operators help combine conditions.