JavaScript Tutorial menu

JavaScript Operators

Operators are symbols that do something with values, like adding numbers or comparing them.

Arithmetic Operators

OperatorMeaningExampleResult
+Add7 + 310
-Subtract7 - 34
*Multiply7 * 321
/Divide7 / 23.5
%Remainder7 % 31
**Power2 ** 38
++Add 1x++x grows by 1
--Subtract 1x--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

OperatorExampleSame as
=x = 5x = 5
+=x += 5x = x + 5
-=x -= 5x = x - 5
*=x *= 5x = x * 5
/=x /= 5x = 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.

OperatorMeaning
==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);     // true

Always 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));                   // false

The 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?

Learn JavaScript with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp