Operators in JavaScript

 Got it! Let's move on to Operators in JavaScript. Operators are special symbols used to perform operations on values and variables.

➕ Arithmetic Operators

These are used for performing mathematical calculations:

Operator Name Description Example Result
+ Addition Adds two numbers. 10 + 5 15
- Subtraction Subtracts the right operand from the left. 10 - 5 5
* Multiplication Multiplies two numbers. 10 * 5 50
/ Division Divides the left operand by the right. 10 / 5 2
% Modulus Returns the remainder of a division. 10 % 3 1
** Exponentiation Raises the first operand to the power of the second. 2 ** 3 8

Special Case: String Concatenation

The + operator also joins strings together (called concatenation):

const firstName = "John";

const lastName = "Doe";

const fullName = firstName + " " + lastName; // Result: "John Doe"


🏷️ Assignment Operators

These are used to assign values to variables. The most basic is the = sign, but there are shorthand versions:

Operator Example Equivalent to
= x = 5 x = 5 (Simple assignment)
+= x += 3 x = x + 3
-= x -= 2 x = x - 2
*= x *= 4 x = x * 4
/= x /= 2 x = x / 2

⚖️ Comparison Operators

These are used to compare two values and always return a Boolean value (true or false). These are crucial for making decisions in your code (which we'll cover with if statements next!).

Operator Name Description Example Result
== Equal to Checks if two values are equal (ignores type). 5 == '5' true
=== Strict Equal Checks if two values are equal and have the same type. (Always use this!) 5 === '5' false
!= Not Equal Checks if values are not equal (ignores type). 5 != 8 true
!== Strict Not Equal Checks if values are not equal or not of the same type. (Always use this!) 5 !== '5' true
> Greater Than Returns true if the left value is greater than the right value. 10 > 5 true
< Less Than Returns true if the left value is less than the right value. 10 < 5 false
>= Greater Than or Equal To Returns true if the left value is greater than or equal to the right value. 10 >= 10 true
<= Less Than or Equal To Returns true if the left value is less than or equal to the right value. 10 <= 9 false


💡 Important Note: The Strict Comparison Operators (=== and !==) are best practice in JavaScript because they prevent unexpected type-coercion issues.


🧠 Logical Operators

These are used to combine multiple Boolean conditions.

Operator Name Description Example
&& AND Returns true if both conditions are true. (5 > 3) && (2 < 4)true
` ` OR
! NOT Reverses the boolean result. !truefalse


Post a Comment

0 Comments