Operators & Logic›Core· 35 min read
Operators
Do maths, join text and update values with JavaScript operators.
What you will learn
- Use arithmetic operators
- Join strings with +
- Use assignment shortcuts
Arithmetic
| Operator | Does | Example |
|---|---|---|
+ | Add (or join text) | 5 + 2 → 7 |
- | Subtract | 5 - 2 → 3 |
* | Multiply | 5 * 2 → 10 |
/ | Divide | 6 / 2 → 3 |
% | Remainder (modulo) | 7 % 2 → 1 |
** | Power | 2 ** 3 → 8 |
Let us put * (multiply) and + (join) to work in one small price calculation.
<script>
let price = 100;
let qty = 3;
let total = price * qty;
document.write("Total: ₹" + total);
</script>Live preview
price * qty multiplies 100 by 3 and stores 300 in total. Then "Total: ₹" + total joins the label text to that number, so the page shows the finished sentence.
Note: Output: Total: ₹300
Assignment shortcuts
Update a variable using its own value: +=, -=, *=. And ++ adds one, -- subtracts one.
<script>
let count = 5;
count += 3; // same as count = count + 3 → 8
count++; // → 9
document.write("Count is " + count);
</script>Live preview
count starts at 5. count += 3 is a shortcut for "take whatever count is and add 3", making it 8. Then count++ adds just one more, making it 9. So the final printed value is 9.
Note: Output: Count is 9
Tip: The % (modulo) operator gives the remainder — perfect for checking even/odd: n % 2 === 0 means n is even.
Q. What does 7 % 3 give?
Answer: % is the remainder. 7 = 3×2 + 1, so 7 ÷ 3 leaves a remainder of 1.
✍️ Practice
- Calculate the total cost of 4 items at ₹250 each and print it.
- Use
%to print whether the number 9 is even or odd (hint:9 % 2).
🏠 Homework
- Write a script that converts a temperature from Celsius to Fahrenheit (
F = C * 9/5 + 32).