Lesson 3: Operators
Basic mathematical operators
Operators are used to carry out an operation to our variables. To add and subtract variables from each other we must use some mathematical operators. Look at the table below and then edit the TRY ME below.
Symbol of Operator | Meaning of Operator |
---|---|
= | Assignment |
+ | Addition |
- | Minus |
* | Multiplication |
/ | Division |
% | Remainder |
let number = 1 + 2;
console.log(number);
Try It!
Switch into the javaScript file below and run the code. Now use a similar format as below to divide 21 by 7 and log the result to the console.
Compound Assignment Operators
Compound operators are abbreviated and compact operators which can carry out the roles of two or more operators. For example the operators in the table below all give a value to an element using an assignment operator while preforming a mathematical calculation on the variable.
Operator | Symbol | Example | Meaning |
Addition assignment | += | x += 3 | x = x + 3 |
Subtraction assignment | -= | x -= 5 | x = x - 5 |
Multiplication assignment | *= | x *= 7 | x = x * 7 |
Division assignment | /= | x /= 9 | x = x / 9 |
Remainder assignment | %= | x %= 11 | x = x % 11 |
Exponentiation assignment | **= | x **= 13 | x = x ** 13 |
let number = 2;
number += 8
console.log(number);
Try It!
See how the code below changes the value of the variable. First we add 5 to the variable and we then subtract 2 from the variable. Now try and create a variable called number and assign it an even number value. Then used the compound divide assignment operator to divide number by 2 and log the result to the console.
Boolean operators
As we can remember from the previous section the Boolean type has two main values; true and false. Boolean operators return either true or false after comparing or checking whether variables, numbers and other objects meet certain criteria. These will be heavily used in the next section, flow and conditionals.
Operator | Symbol | Explanation |
Equal | == | Returns true if operands are equal |
Not equal | != | Returns true if operands are not equal |
Strict equal | === | Returns true if operands are equal and are of the same data type |
Strict not equal | !== | Returns true if operands are not equal or if they are not the same data type |
Less than | < | Returns true if the first operand is less than in value of the second operand |
Greater than | > | Returns true if the first operand is greater in value than the second operand |
Less than or equal to | <= | Returns true if the first operand is less than or equal to the value of the second value |
Greater than or equal to | >= | Returns true if the first operand is greater than or equal to the value of the second value |
Further Reading