JavaScript operators are essential tools for performing various operations on values and variables. In this guide, we’ll explore the different types of operators in JavaScript and provide code examples to help you understand how each one works.
Arithmetic operators are used for basic mathematical operations:
+
-
*
/
%
**
(ES6)Example:
let addition = 5 + 3; // 8
let subtraction = 10 - 4; // 6
let multiplication = 4 * 6; // 24
let division = 15 / 3; // 5
let modulus = 17 % 4; // 1
let exponentiation = 2 ** 3; // 8
Assignment operators are used to assign values to variables and update their values:
=
+=
-=
*=
/=
%=
**=
(ES6)Example:
let x = 5;
x += 3; // x is now 8
x -= 2; // x is now 6
x *= 4; // x is now 24
x /= 6; // x is now 4
x %= 3; // x is now 1
x **= 2; // x is now 1 (ES6)
Comparison operators are used for comparing values:
==
(type coercion)===
!=
(type coercion)!==
>
<
>=
<=
Example:
let isEqual = 5 == "5"; // true
let isStrictEqual = 5 === "5"; // false
let isNotEqual = 5 != 8; // true
let isNotStrictEqual = 5 !== 8; // true
let isGreater = 10 > 7; // true
let isLess = 3 < 2; // false
let isGreaterOrEqual = 6 >= 6; // true
let isLessOrEqual = 5 <= 4; // false
Logical operators are used for combining and manipulating boolean values:
&&
||
!
Example:
let logicalAnd = true && false; // false
let logicalOr = true || false; // true
let logicalNot = !true; // false
Unary operators operate on a single operand or variable:
++
--
-
typeof
void
delete
Example:
let number = 5;
number++; // Increment (6)
number--; // Decrement (5)
let negate = -number; // Negation (-5)
let type = typeof number; // Typeof operator
Bitwise operators are used for binary-level operations:
&
|
^
~
<<
>>
>>>
Example:
let a = 5; // Binary: 0101
let b = 3; // Binary: 0011
let bitwiseAnd = a & b; // 1 (Decimal)
let bitwiseOr = a | b; // 7 (Decimal)
let bitwiseXor = a ^ b; // 6 (Decimal)
let bitwiseNot = ~a; // Negative decimal number
let leftShift = a << 2; // 20 (Decimal)
let rightShift = a >> 1; // 2 (Decimal)
let unsignedRightShift = a >>> 1; // 2 (Decimal)
These are the fundamental JavaScript operators that you’ll use in your coding journey. Understanding how each operator works is crucial for writing efficient and error-free code. Experiment with these operators to gain a deeper understanding of their functionality. Happy coding!
In the world of C# and object-oriented programming (OOP), classes and objects form the backbone…
In modern C# programming, working with data collections is a common task. Understanding how to…
Exception handling is a critical part of writing robust and maintainable C# applications. It allows…
One of the common questions among Docker users is whether Docker containers consume disk space.…
Sorting data is a common operation in programming, allowing you to organize information in a…
Splitting a string into an array of substrings is a common operation in C# programming,…