Operators in JavaScript
In this article, we will explain operators in JavaScript.
YouTube Video
Operators in JavaScript
Operators in JavaScript are symbols or keywords used to perform calculations or comparisons on numbers and variables. There are various types of operators, each performing different operations. Here are some of the main operators summarized:.
Arithmetic Operators
JavaScript's arithmetic operators include the following:.
Operator | Description | Example | Result |
---|---|---|---|
+ |
Addition | 5 + 2 |
7 |
- |
Subtraction | 5 - 2 |
3 |
* |
Multiplication | 5 * 2 |
10 |
/ |
Division | 5 / 2 |
2.5 |
% |
Modulus (Remainder) | 5 % 2 |
1 |
++ |
Increment (Increase by 1) | let x = 5; x++ |
6 |
-- |
Decrement (Decrease by 1) | let x = 5; x-- |
4 |
1let a = 10; // Initialize variable 'a' with the value 10
2let b = 3; // Initialize variable 'b' with the value 3
3
4// Perform and display arithmetic operations between 'a' and 'b'
5console.log("Addition (a + b): ", a + b); // 13
6console.log("Subtraction (a - b): ", a - b); // 7
7console.log("Multiplication (a * b):", a * b); // 30
8console.log("Division (a / b): ", a / b); // 3.333...
9console.log("Modulus (a % b): ", a % b); // 1
10
11// Demonstrate post-increment operation on 'a'
12// Output the current value of 'a' (10), then increment
13console.log("Post-increment (a++): ", a++);
14// Display the incremented value of 'a' (11)
15console.log("Value of 'a' after increment:", a);
16
17// Demonstrate pre-increment operation on 'a'
18// Increment 'a' first (12) then output
19console.log("Pre-increment (++a): ", ++a);
20
21// Demonstrate post-decrement operation on 'a'
22// Output the current value of 'a' (12), then decrement
23console.log("Post-decrement (a--): ", a--);
24// Display the decremented value of 'a' (11)
25console.log("Value of 'a' after decrement:", a);
26
27// Demonstrate pre-decrement operation on 'a'
28// Decrement 'a' first (10) then output
29console.log("Pre-decrement (--a): ", --a);
Arithmetic operators perform basic mathematical operations on numbers. In addition to addition and subtraction, you can perform operations such as modulus, increment, and decrement. Note that the value returned by increment or decrementing differs depending on whether the operator is placed before or after the operand.
Assignment Operators
JavaScript's assignment operators include the following:.
Operator | Description | Example | Result |
---|---|---|---|
= |
Assignment | x = 5 |
x is assigned the value 5 |
+= |
Addition assignment | x += 5 |
x = x + 5 |
-= |
Subtraction assignment | x -= 5 |
x = x - 5 |
*= |
Multiplication assignment | x *= 5 |
x = x * 5 |
/= |
Division assignment | x /= 5 |
x = x / 5 |
%= |
Modulus assignment | x %= 5 |
x = x % 5 |
1let x = 10;
2
3x += 5; // x = x + 5, so x becomes 15
4console.log('After x += 5 : ', x); // 15
5
6x -= 10;
7console.log('After x -= 10 : ', x); // 5
8
9x *= 3;
10console.log('After x *= 3 : ', x); // 15
11
12x /= 3;
13console.log('After x /= 3 : ', x); // 5
14
15x %= 2;
16console.log('After x %= 2 : ', x); // 1
Assignment operators are used to assign values to variables or update the values of variables. In addition to regular assignment, there are assignment operators for arithmetic operations like addition and modulus.
Comparison Operators
JavaScript's comparison operators include the following:.
Operator | Description | Example | Result |
---|---|---|---|
== |
Equal | 5 == "5" |
true |
=== |
Strictly Equal (Both type and value are equal) | 5 === "5" |
false |
!= |
Not Equal | 5 != "5" |
false |
!== |
Strictly Not Equal | 5 !== "5" |
true |
> |
Greater Than | 5 > 2 |
true |
< |
Less Than | 5 < 2 |
false |
>= |
Greater Than or Equal To | 5 >= 5 |
true |
<= |
Less Than or Equal To | 5 <= 4 |
false |
1console.log("5 == '5' evaluates to:", 5 == "5"); // true (because the values are equal)
2console.log("5 === '5' evaluates to:", 5 === "5"); // false (because the types are different)
3console.log("5 != '5' evaluates to:", 5 != "5"); // false
4console.log("5 !== '5' evaluates to:", 5 !== "5"); // true
5console.log("5 > 2 evaluates to:", 5 > 2); // true
6console.log("5 < 2 evaluates to:", 5 < 2); // false
7console.log("5 >= 5 evaluates to:", 5 >= 5); // true
8console.log("5 <= 4 evaluates to:", 5 <= 4); // false
9console.log("5 >= '5' evaluates to:", 5 >= "5"); // true
10console.log("5 <= '5' evaluates to:", 5 <= "5"); // true
- Comparison operators compare values and return either true or false.
- The equality operator (
==
) automatically converts different types if necessary before performing the comparison. The strict equality operator (===
) does not perform any type conversion during comparison and returnstrue
only if both values have the same type and the same value. Using the strict equality operator (===
) helps prevent bugs caused by unintended type conversion, so it is recommended to use it preferentially.
Logical Operators
JavaScript's logical operators include the following:.
Operator | Description | Example | Result |
---|---|---|---|
&& |
AND (True if both conditions are true) | true && false |
false |
|| |
OR (True if either condition is true) | true || false |
true |
! |
NOT (Turns true to false and false to true) | !true |
false |
1let a = true;
2let b = false;
3
4console.log("a && b evaluates to:", a && b); // false
5console.log("a || b evaluates to:", a || b); // true
6console.log("!a evaluates to:", !a); // false
Logical operators are used when there are multiple conditions, to evaluate combinations of conditions.
Priority of Logical Operators
In JavaScript, logical operators are generally evaluated in the order of NOT
first, followed by AND
, and finally OR
.
NOT
has the highest precedence
NOT
is a unary operator and is evaluated with the highest precedence.
1console.log(!true || false); // false
AND
takes precedence over OR
AND
has higher precedence than OR
, so the AND
part is evaluated first.
1console.log(true || false && false); // true
In this way, the AND
(&&
) part is evaluated first, and its result is passed to OR
(||
).
AND
and OR
perform short-circuit evaluation
JavaScript's AND
and OR
perform short-circuit evaluation. If the result can be determined by the left-side value, the right-side expression is not evaluated.
1let a = false && console.log("This will not be printed");
2console.log(a); // false
3
4let b = true || console.log("This will not be printed");
5console.log(b); // true
In either case, console.log()
will not be executed.
Establish explicit precedence
By explicitly grouping expressions with parentheses, you can prevent misunderstandings about precedence.
1console.log(true || (false && false)); // true
Differences between natural language and program interpretation
When using logical operators, it's important to be aware of the ambiguities in natural language. For example, when saying 'white dog or cat,' it could mean either 'a white dog or any color of cat' or 'a white dog or a white cat.'. In code, it would look like this:.
1if (isWhite && isDog || isCat) {
2 console.log(' "A white dog" or "a cat of any color" ');
3}
4
5if (isWhite && (isDog || isCat)) {
6 console.log(' "A white dog" or "a white cat" ');
7}
8
9console.log(true || (false && false)); // true
As natural language contains ambiguities like this, care is needed when coding or designing.
Ternary Operator (Conditional Operator)
JavaScript includes a ternary operator (conditional operator).
Operator | Description | Example | Result |
---|---|---|---|
? : |
If the condition is true, the left side is executed, if false, the right side | condition ? if true : if false |
Result based on the condition |
1let age = 20;
2let message = age >= 18 ? "Adult" : "Minor";
3console.log(message); // "Adult"
It is written in the form condition ? value if true : value if false
.
Bitwise Operators
JavaScript bitwise operators include the following.
Operator | Description | Example | Result |
---|---|---|---|
& |
AND | 5 & 1 |
1 |
| |
OR | 5 | 1 |
5 |
^ |
XOR | 5 ^ 1 |
4 |
~ |
NOT | ~5 |
-6 |
<< |
Left Shift | 5 << 1 |
10 |
>> |
Right Shift | 5 >> 1 |
2 |
1let x = 0x0F & 0x0C;
2console.log("0x0F & 0x0C evaluates to:", x, "(0x0C, 12)"); // 0x0C (12)
3
4x = 0x04 | 0x02;
5console.log("0x04 | 0x02 evaluates to:", x, "(0x06, 6)"); // 0x06 (6)
6
7x = 0x0F ^ 0x0C;
8console.log("0x0F ^ 0x0C evaluates to:", x, "(0x03, 3)"); // 0x03 (3)
9
10// The inverted number is represented as a negative value
11// because JavaScript numbers are stored as signed 32-bit integers.
12x = ~0x0C;
13console.log("~0x0C evaluates to:", x, "(-13, 0xF3)"); // 0xF3 (-13)
14
15x = 0x04 << 1;
16console.log("0x04 << 1 evaluates to:", x, "(0x08, 8)"); // 0x08 (8)
17x = 0x04 >> 1;
18console.log("0x04 >> 1 evaluates to:", x, "(0x02, 2)"); // 0x02 (2)
Bit operators perform calculations on numbers at the bit level. They are usually used for low-level processing.
Type Operators
JavaScript type operators include the following.
Operator | Description | Example | Result |
---|---|---|---|
typeof |
Returns the type of a variable | typeof 123 |
"number" |
instanceof |
Checks if an object belongs to a specific class | arr instanceof Array |
true |
1console.log(typeof "Hello"); // "string"
2console.log(typeof 42); // "number"
3
4let arr = [1, 2, 3];
5console.log("arr instanceof Array : ", arr instanceof Array); // true
Type operators are used to check the type of a value or to convert it to a specific type.
The typeof
operator returns the type of a variable.
The instanceof
operator checks whether an object belongs to a specific class.
Summary
- Arithmetic operators perform basic calculations.
- Assignment operators assign or update values in variables.
- Comparison operators compare two values and return true or false.
- Logical operators evaluate combinations of conditions.
- Ternary operators allow you to write conditional statements in a shorter form than
if
. - Bitwise operators perform calculations at the bit level.
- Type operators allow you to check the type of a value.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.