JavaScript Operators: A Complete Tutorial
#JavaScript Operars: A Complete Tutorial
Operators in JavaScript are symbols used to perform operations on values and variables. They are fundamental to building expressions and implementing logic in your code. In this tutorial, we’ll cover the various types of JavaScript operators with examples.
These are used to perform basic mathematical operations:
Operator | Description | Example | Result |
---|---|---|---|
+ |
Addition |
5 + 3 |
8 |
- |
Subtraction |
5 - 3 |
2 |
* |
Multiplication |
5 * 3 |
15 |
/ |
Division |
6 / 2 |
3 |
% |
Modulus (Remainder) |
5 % 2 |
1 |
** |
Exponentiation |
2 ** 3 |
8 |
++ |
Increment |
a++ |
a = a + 1 |
-- |
Decrement |
a-- |
a = a - 1 |
These are used to assign values to variables.
Operator | Example | Equivalent To |
---|---|---|
= |
x = 10 |
Assign 10 to x |
+= |
x += 5 |
x = x + 5 |
-= |
x -= 3 |
x = x - 3 |
*= |
x *= 2 |
x = x * 2 |
/= |
x /= 4 |
x = x / 4 |
%= |
x %= 2 |
x = x % 2 |
**= |
x **= 2 |
x = x ** 2 |
These compare two values and return a Boolean (true
or false
).
Operator | Description | Example | Result |
---|---|---|---|
== |
Equal to (loose) |
5 == '5' |
true |
=== |
Equal to (strict) |
5 === '5' |
false |
!= |
Not equal (loose) |
5 != '5' |
false |
!== |
Not equal (strict) |
5 !== '5' |
true |
> |
Greater than |
5 > 3 |
true |
< |
Less than |
5 < 3 |
false |
>= |
Greater than or equal |
5 >= 5 |
true |
<= |
Less than or equal |
5 <= 4 |
false |
Used to combine conditional statements.
Operator | Description | Example | Result |
---|---|---|---|
&& |
Logical AND |
true && false |
false |
` | ` | Logical OR | |
! |
Logical NOT |
!true |
false |
JavaScript uses the +
operator to concatenate strings.
let greeting = "Hello" + " " + "World"; // "Hello World"
You can also use +=
to append strings:
let name = "John";
name += " Doe"; // "John Doe"
typeof
Returns the type of a variable.
typeof "hello"; // "string"
typeof 42; // "number"
instanceof
Checks if an object is an instance of a specific class.
let date = new Date();
console.log(date instanceof Date); // true
These perform operations on binary representations of numbers.
Operator | Name | Example |
---|---|---|
& |
AND |
5 & 1 |
` | ` | OR |
^ |
XOR |
5 ^ 1 |
~ |
NOT |
~5 |
<< |
Left shift |
5 << 1 |
>> |
Right shift |
5 >> 1 |
JavaScript operators are powerful tools for building logic, manipulating data, and controlling program flow. Mastering them is crucial for any developer looking to write clean and efficient JavaScript code.
Practice combining these operators in real examples and you'll quickly become comfortable using them in your projects!