Skip to content

Operators

If you have been following this lessons in the order listed, we have already covered many operators. But here I’d like to cover operators a bit more in depth.

Expressions

As mentioned in a previous lesson, an expression is a unit of code that resolves to a value. To expand on this, and expression may have side effects such as assigning a value to a variable, or an expression may simply evaluate.

Regardless of the outcome, an expression will always have an operator and at least one operand.

Operators and Operands

Consider the following:

let x = 4;
x <= 5;
x = 4 + 5;

In the above, x, 4 and 5 are operands. The = and the <= are operators. The first expression is using the assignment operator (=) to assign the value of four to the variable x. The second expression is using a comparison operator (<=) which mean less than or equal to and this expression will resolve to true because 4 is in fact less than or equal to 5. The last expression is using both an assignment operator (=) and an arithmetic operator (+). The arithmetic operator will resolve the right hand side of the assignment operator to a value, that being 4 plus 5, or 9. The assignment operator then assigns the value 9 to the variable x.

All of the above operators are considered binary operators, which means that there is an operand on the left side, and operator in the middle, and a second operand on the right side. Even the last expression contains only binary operators, where the second operand relative to the assignment operator is itself a binary operation.

Expressions only one operand and one operator are known as unary operators. Examples include x++ or !x.

I will not comprehensively cover the operators of JavaScript, but the following is a table of the common operators, the type of operator they are, and a description.

OperatorTypeDescriptionExample
=AssignmentThe assignment operator assigns a value to a variablex = 5
==ComparisonThe equality operator compares two values while performing coercion.foo == "bar"
x == 5
42 == "42"
!=ComparisonNot equal, the inverse of the equality operatorx != 4
===ComparisonStrict equality does not coerce the types of the valuesfoo === "bar"
4 === 4
!==ComparisonStrict inequality, the inverse of strict equality4 !== "4"
<ComparisonLess than4 < x
>comparisonGreater than6 > x
<=ComparisonLess than or equal to4 <= x
>=comparisonGreater than or equal to6 >= x
+ArithmeticActs as arithmetic addition for numbers as well as concatination for strings4 + 5
"hello" + " world"
-ArithmeticSubtraction5 - 4
*ArithmeticMultiplication5 * 4
/ArithmeticDivision5 / 4
%ArithmeticModulo returns the remander of a division4 % 2
**ArithmeticExponentx ** 2
++ArithmeticIncrement by 1x++ ++x
--ArithmeticDecrement by 1x-- --x
&&LogicalAND operator returns true if both operands evaluate to truex == 5 && y < x
||LogicalOR operator returns true if either or both operands evaluate to truex == 5 || x == 3