JavaScript Operators
work in progress, last updated: May 14, 2020Introduction
In JavaScript operators are used to perform math operations on variables and values, check if they fullfil a condition, and give more use to our functions. The following math operations are supported: Addition +, Subtraction -, Multiplication *, Division /, Remainder %, and Exponentiation **. In Addition; there is a set of comparison and logical operators.
Primary calculation operators
The primary operator in math are addition, subtraction, amultiplication and division. They are straightforward! Below are some examples;
console.log( 2 + 2 ); // 4
console.log( 8 - 3 ); // 5
console.log( 4 * 5 ); // 20
console.log( 15 / 3 ); // 5
Remainder %
The remainder operator %, despite its appearance, is not related to percents. The result of a % b is the remainder of the integer division of a by b.
console.log( 5 % 2 ); // 1, a remainder of 5 divided by 2
console.log( 8 % 3 ); // 2, a remainder of 8 divided by 3
Exponentiation **
The exponentiation operator a ** b multiplies a by itself b times.
console.log( 2 ** 2 ); // 4 (2 multiplied by itself 2 times)
console.log( 2 ** 3 ); // 8 (2 * 2 * 2, 3 times)
console.log( 2 ** 4 ); // 16 (2 * 2 * 2 * 2, 4 times)
console.log( 4 ** (1/2) ); // 2 (power of 1/2 is the same as a square root)
console.log( 8 ** (1/3) ); // 2 (power of 1/3 is the same as a cubic root)
Comparision & Logical operators
Comparison operators are operators that compare values and return true or false . The operators
include: > , < ,>= , <= ,===, and ! (not).
Logical operators are operators that combine multiple boolean
expressions or values and provide
a single boolean output. The operators include: && , || , and ! .
Below are some examples of how these
operators are used as conditions in functions
if(num > 5) {
console.log("Simple check:", "TRUE!");
}
if(num === 5) {
console.log("Strict equality:", "TRUE!");
}
if(num > 5 || num2 < 30) {
console.log("Double check with OR:", "TRUE");
}
if(num > 5 && num2 < 30) {
console.log("Double check with AND:", "TRUE");
}
if(num != "5") {
console.log("not operator: TRUE!");
}