Operators in JavaScript
Operators are special symbols or keywords used to perform operations on values or variables. They're the building blocks of logic and calculations in your programs.
JavaScript provides many types of operators, and each type does something different.
1. Arithmetic Operators
Used for performing basic math:
Operator | Description | Example | Result |
---|---|---|---|
+ | Addition | 5 + 2 | 7 |
- | Subtraction | 5 - 2 | 3 |
* | Multiplication | 5 * 2 | 10 |
/ | Division | 10 / 2 | 5 |
% | Modulus (remainder) | 5 % 2 | 1 |
** | Exponentiation | 2 ** 3 | 8 |
++ | Increment | x++ | Adds 1 |
-- | Decrement | x-- | Subtracts 1 |
2. Assignment Operators
Used to assign values to variables.
Operator | Example | Same As |
---|---|---|
= | x = 5 | Assign 5 to x |
+= | x += 2 | x = x + 2 |
-= | x -= 2 | x = x - 2 |
*= | x *= 2 | x = x * 2 |
/= | x /= 2 | x = x / 2 |
%= | x %= 2 | x = x % 2 |
3. Comparison Operators
Used to compare two values. These return a Boolean (true or false).
Operator | Description | Example | Result |
---|---|---|---|
== | Equal (loose) | 5 == "5" | true |
=== | Equal (strict) | 5 === "5" | false |
!= | Not equal (loose) | 5 != "5" | false |
!== | Not equal (strict) | 5 !== "5" | true |
> | Greater than | 6 > 3 | true |
<< /td> | Less than | 3 < 6 | true |
>= | Greater than or equal to | 5 >= 5 | true |
<=< /td> | Less than or equal to | 5 <= 4 | false |
4. Logical Operators
Used to combine multiple conditions.
Operator | Description | Example | Result |
---|---|---|---|
&& | Logical AND | true && false | false |
|| | Logical OR | true || false | true |
! | Logical NOT | !true | false |
5. Type Operators
Operator | Description | Example |
---|---|---|
typeof | Returns the type of a variable | typeof "hello" → "string" |
instanceof | Checks if object is an instance of a class | obj instanceof Object |
Bonus: String Concatenation
The + operator is also used to join strings:
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName); // John Doe