Operators can be as simple as math, like what we learn from school! In this JavaScript operators lesson, we are going to learn math operators, comparison operators, and assignment operators.
Math Operators
Math operators are like addition +
, subtraction -
, multiplication *
, division /
, and so on. Let’s take a look at the examples below!
Addition (+
)
let x = 5;
let y = 10;
let z = x + y;
alert(z);
Subtraction (-
)
Multiplication (*
)
Division (/
)
Division Remainder (%
)
Try It Out
Assignment Operators
Assignment operators are a shortcut to make your code look nicer and easier to read.
Assignment (=
)
The assignment operator just saves the value on the right into the variable on the left like we did before.
let x = "Annie";
alert(x);
Addition Assignment (+=
)
Addition assignment is just a shorter way of writing x = x + number
.
Instead of this:
let x = 15;
x = x + 5;
alert(x);
// x = 20
Do this:
let x = 15;
x += 5;
alert(x);
// x = 20
This similar to using “change by” in Scratch as opposed to “set to.”
Subtraction Assignment (-=
)
Subtraction assignment is just a shorter way of writing x = x - number
.
Instead of this:
let x = 8;
x = x - 5;
alert(x);
// x = 3
Do this:
let x = 8;
x -= 5;
alert(x);
// x = 3
Multiplication Assignment (*=
)
Subtraction assignment is just a shorter way of writing x = x * number
.
Instead of this:
let x = 3;
x = x * 2;
alert(x);
// x = 6
Do this:
let x = 3;
x *= 2;
alert(x);
// x = 6
Division Assignment (/=
)
Division assignment is just a shorter way of writing x = x / number
.
Instead of this:
let x = 8;
x = x / 2;
alert(x);
// x = 4
Do this:
let x = 8;
x /= 2;
alert(x);
// x = 4