Mathematical operations have been familiar to us since school: addition (+
), multiplication (*
), subtraction (-
), division (/
) and so on. Before we move on, let's explore the terminology in regards to JavaScript.
The operand is what the operator applies to in JS code. For example, in the 5*2 multiplication, there are two operands: the left operand is 5 and the right operand is 2. They are sometimes referred to as arguments instead of operands.
Unary is an operator that applies to a single operand. For example, the unary minus operator (-) reverses the sign of a number:
let operand = 1;
operand = -operand;
console.log(operand);
Binary is an operator that applies to two operands.
let operand1 = 1;
let operand2 = 3;
console.log(operand2 - operand1);
Types of JavaScript operators
Assignment operators
An assignment operator is there to assign a left operand value based on a right operand value. The basic one is an equal (=
), and that would be x = f()
, assigning the value of f()
to x
.
Example: Assigning to properties.
let myObj = {};
myObj.firstProperty = 3;
console.log(myObj.firstProperty); // Output 3.
console.log(myObj); // Output { firstProperty: 3 }.
const myKey = "y";
myObj[myKey] = 5;
console.log(myObj[myKey]); // Output 5.
console.log(myObj); // Output { firstProperty: 3, y: 5 }.
Comparison operators
A comparison operator compares its operands and returns a logical value based on whether the comparison is true. In JavaScript, they are written like this:
Greater / less: a > b
, a < b.
Greater / less or equal: a >= b
, a <= b.
Equal: a == b
Not equal: a != B
Note that the comparison uses the double equal sign ==
. A single equal sign a = b
would mean an assignment.
In mathematics, it is denoted by the symbol ≠, but in JavaScript it is written as a != B
.
alert( 3 > 2 ); // true
alert( 4 == 2 ); // false
alert( 5 != 1 ); // true
The result of the comparison can be assigned to a variable, just like any value:
let result = 7 > 5;
console.log(result);
Let's compare strings. The algorithm for comparing two strings is pretty simple:
The first characters of strings are compared first.
If the first character of the first line is greater (or less) than the first character of the second string, then the first character is greater (or less) than the second character. The comparison is complete.
If the first characters are equal, then the second characters of the strings are compared in the same way.
The comparison continues until one of the lines ends.
If both lines end at the same time, then they are equal. Otherwise, the longer the string is considered.
console.log("Z" > "A"); // true
console.log("Cat" < "Cats");// true
console.log("Wonderful" > "Wonder");// true
Comparison of different types
When comparing values of different types, JavaScript converts each values to a number.
console.log("3" > 2); // true,
console.log("01" == 1);// true,
The boolean value true becomes 1, and false becomes 0.
console.log(true == 1); // true
console.log(false == 0); // true
Strict comparison
The strict equality operator (===
) tests equality without typecasting. In other words, if a
and b
are of different types, then the test a === b
immediately returns false without trying to convert them.
console.log(0 === false); // false
The values null and undefined are equal (==
) to each other and are not equal to any other value.
console.log(undefined > 0); // false
console.log(undefined < 0); // false
console.log(undefined == 0); // false
console.log(null > 0); // false
console.log(null < 0); // false
console.log(null == 0); // false
console.log(null >= 0); // true
Comparisons convert null to a number, treating it as 0. Therefore, expression (3) null >= 0
is true
, and null > 0
is false
. Be careful when using comparison operators like >
and <
with null
/undefined
variables. It's a good idea to do a separate null
/undefined
check.
Arithmetic operators
An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The following mathematical operators are supported:
Addition
console.log(5 + 7); // output 12
Subtraction
console.log(6 - 3); // output 3
Multiplication
console.log(9 * 3); // output 27
Division
console.log(15 / 3); // output 5
Taking the remainder of the division
console.log(5 % 2); // output 1
console.log(8 % 3); // output 2
Exponentiation
console.log(3 ** 5); // output 243
Bitwise operators
Bitwise operators operate on 32-bit integers (cast if necessary), at the level of their internal binary representation. These operators are not JavaScript specific, they are supported in most programming languages.
The following bitwise operators are supported:
AND (and) (&)
OR (or) (|)
XOR (bitwise exclusive or) (^)
NOT (not) (~)
LEFT SHIFT (<<)
RIGHT SHIFT (>>)
ZERO-FILL RIGHT SHIFT (>>>)
Logical operators
There are three logical operators in JavaScript: ||
(OR), &&
(AND) and !
(NOT).
|| (OR)
let result = x || z;
This operator (||
) performs the following actions:
It calculates operands from left to right.
Each operand converts to a
boolean
value. If the result istrue
, it stops and returns the original value of this operand.If all operands are
false
, it returns the last one.
The value is returned without conversion. In other words, the OR chain returns the first true value, or the last if no such value was found.
console.log(1 || 0); // 1
console.log(null || 0 || 1); // 1
&& (AND)
let result = x && z;
The &&
operator does the following:
It calculates operands from left to right.
Each operand converts to a
boolean
value. If the result isfalse
, it stops and returns the original value of this operand.If all operands are
true
, the last one is returned.
In other words, AND
returns the first false
value. Or the latter, if nothing was found.
console.log(null && 5); // null
console.log(1 && 5); // 5
console.log(0 && "no matter what"); // 0
! (NOT)
let result = !val;
The operator takes one argument and does the following:
First, it casts the argument to the
boolean
typetrue
/false
.Then it returns the opposite value.
console.log(!true); // false
console.log(!0); // true
String operators
Usually numbers are added using the plus sign (+
). But if the binary operator is applied to strings, it merges them:
let myString = "My" + " " + "string";
console.log(myString);
// output My string
Note that if at least one operand is a string
, then the second will also be converted to a string
.
console.log("1" + 2); //12
Conditional (ternary) operators
The operator is represented by a question mark (?
). It is also called ternary because this operator, which is the only one of its kind, has three arguments.
Syntax
condition ? val1 : val2
The condition is evaluated first: if it is true
, then value1 is returned, otherwise - value2.
let accessKey = age > 21 ? true : false;
console.log(accessKey);
Operator priority
In the event that there are several operators in the expression, the order of their execution is determined by priority, or, in other words, there is a certain order of execution of the operators.
We know from school that the multiplication in the expression 1 + 2 * 2 will be performed before the addition. This is precisely the "priority". Multiplication is said to take precedence over addition.
The parentheses are more important than priority, so if we're not satisfied with the default ordering, we can use them to change the priority. For example, write (1 + 2) * 2.
There are many operators in JavaScript. Each operator has a corresponding priority number. The one with the higher number will be executed earlier. If the priority is the same, then the order of execution is from left to right.
Here is the Table of operator's priority:
Comma / Sequence (
,
)Assignment (
=
,+=
,-=
,**=
,*=
,/=
,%=
,<<=
,>>>=
,&=
,^=
,|=
,&&=
,||=
,??=
), yield (yield
), yield* (yield*
)Logical OR (
||
), Nullish coalescing operator (??
)Logical AND (
&&
)Bitwise OR (
|
)Bitwise XOR (
^
)Bitwise AND (
&
)Equality (
==
), Inequality (!=
), Strict Equality (===
), Strict Inequality (!==
)Less Than (
<
), Less Than Or Equal (<=
), Greater Than (>
), Greater Than Or Equal (>=
), in (in
), instance of (instanceof
)Bitwise Left Shift (
<<
), Bitwise Right Shift (>>
), Bitwise Unsigned Right Shift (>>>
)Addition (
+
), Subtraction (-
)Multiplication (
*
), Division (/
), Remainder (%
)Exponentiation (
**
)Logical NOT (
!
), Bitwise NOT (~
), Unary plus (+
), Unary negation (-
), Prefix Increment (++...
), Prefix Decrement (--...
), type of (typeof
), void (void
), delete (delete
), await (await
)Postfix Increment (
...++
), Postfix Decrement (...--
)new without argument list (
new
)Member Access (
… . …
), Computed Member Access (… [ … ]
), new with argument list (new … ( … )
), Function Call (… ( … )
), Optional chaining (?.
)Grouping (
...
)
Test yourself
Task 1. What will be the result of the expressions below?
console.log("" + 1 + 0);
console.log("" - 1 + 0);
console.log(true + false);
console.log(6 / "3");
console.log("2" * "3");
console.log(4 + 5 + "px");
console.log("$" + 4 + 5);
console.log("4" - 2);
console.log("4px" - 2);
console.log(7 / 0);
console.log(" -9 " + 5);
console.log(" -9 " - 5);
console.log(null + 1);
console.log(undefined + 1);
console.log(" \t \n" - 2);
Solution
console.log("" + 1 + 0); // 10
console.log("" - 1 + 0); //-1
console.log(true + false); //1
console.log(6 / "3"); //2
console.log("2" * "3"); //6
console.log(4 + 5 + "px"); //9px
console.log("$" + 4 + 5); //$45
console.log("4" - 2); //2
console.log("4px" - 2); //NaN
console.log(7 / 0); //Infinity
console.log(" -9 " + 5); // -9 5
console.log(" -9 " - 5); //-14
console.log(null + 1); //1
console.log(undefined + 1); //NaN
console.log(" \t \n" - 2); //-2
Task 2. What will the code below output?
console.log(console.log(1) && console.log(2));
Solution
Output 1 and then undefined
Task 3. Write an
if
condition to test that age is NOT between 25 and 100, inclusive.
Solution
if (!(userAge >= 25 && userAge <= 100));
Task 4. What will the code below output?
console.log(null || 2 || undefined);
Solution
Output 2, this is the first value that will give true
in a boolean
context.
Task 5. What will be the result of the expressions below?
console.log(15 > 14);
console.log("pineapple" > "apple");
console.log("3" > "13");
console.log(undefined == null);
console.log(undefined === null);
console.log(null == "\n0\n");
console.log(null === +"\n0\n");
Solution
console.log(15 > 14); //true
console.log("pineapple" > "apple"); //true
console.log("3" > "13"); //true
console.log(undefined == null); //true
console.log(undefined === null); // false
console.log(null == "\n0\n"); // false
console.log(null === +"\n0\n"); // false
Task 6. What will the code below output?
console.log(1 && null && 2);
Solution
console.log(1 && null && 2); //Output null
Null
because it is the first false
value in the list.