JavaScript Operators
Operators are symbols that do something with values, like adding numbers or comparing them.
Arithmetic Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 7 + 3 | 10 |
- | Subtract | 7 - 3 | 4 |
* | Multiply | 7 * 3 | 21 |
/ | Divide | 7 / 2 | 3.5 |
% | Remainder | 7 % 3 | 1 |
** | Power | 2 ** 3 | 8 |
++ | Add 1 | x++ | x grows by 1 |
-- | Subtract 1 | x-- | x shrinks by 1 |
Example
html
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
let apples = 17;
let perBox = 5;
let boxes = Math.floor(apples / perBox);
let left = apples % perBox;
document.getElementById("demo").innerHTML = boxes + " full boxes, " + left + " apples left over";
</script>
</body>
</html>Try it Yourself »Output
3 full boxes, 2 apples left over
Like in maths, * and / are done before + and -. Use brackets to change the order: (2 + 3) * 4 is 20.
Assignment Operators
| Operator | Example | Same as |
|---|---|---|
= | x = 5 | x = 5 |
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
Example
javascript
let points = 10;
points += 5;
points *= 2;
console.log(points);Output
30
Adding Strings
The + operator also joins strings. If you add a number and a string, the number becomes text.
Example
javascript
let first = "Ali";
let last = "Raza";
console.log(first + " " + last);
console.log("5" + 5);
console.log(5 + 5 + "5");Output
Ali Raza 55 105
In the last line, 5 + 5 is done first (10), then "5" is joined to it.
Comparison Operators
Comparisons give true or false.
| Operator | Meaning |
|---|---|
== | Equal value (converts types first) |
=== | Equal value and equal type |
!= | Not equal value |
!== | Not equal value or type |
> and < | Greater than, less than |
>= and <= | Greater or equal, less or equal |
Example
javascript
console.log(5 == "5"); // true, the string is converted
console.log(5 === "5"); // false, number vs string
console.log(10 > 7); // trueAlways use === and !==. The loose == converts types in surprising ways, which leads to hidden bugs.
Logical Operators
&&(and): true only if both sides are true||(or): true if at least one side is true!(not): flips true to false and false to true
Example
javascript
let marks = 72;
let attendance = 85;
console.log(marks >= 50 && attendance >= 75); // true: both pass
console.log(marks >= 90 || attendance >= 90); // false: neither
console.log(!(marks >= 50)); // falseThe typeof Operator
typeof tells you the type of a value:
Example
javascript
console.log(typeof 42); // "number"
console.log(typeof "Karachi"); // "string"Exercise
Exercise
What is the result of 10 % 4 in JavaScript?
