JavaScript Operators

Operators are special symbols that perform operations on values (operands). JavaScript has a rich set of operators that are essential for performing calculations, making comparisons, and controlling program flow.

Arithmetic Operators

These operators perform mathematical calculations.

Operator Description Example
+ Addition let sum = 10 + 5; // sum is 15
- Subtraction let difference = 10 - 5; // difference is 5
* Multiplication let product = 10 * 5; // product is 50
/ Division let quotient = 10 / 5; // quotient is 2
% Modulus (Remainder) let remainder = 10 % 3; // remainder is 1
++ Increment let x = 5; x++; // x is now 6
-- Decrement let y = 5; y--; // y is now 4

Assignment Operators

These operators assign values to variables. They can also perform arithmetic operations before assigning the result.

Operator Example Equivalent To
= x = y; x = y
+= x += y; x = x + y
-= x -= y; x = x - y
*= x *= y; x = x * y
/= x /= y; x = x / y
%= x %= y; x = x % y

Comparison Operators

These operators compare two values and return a boolean result (true or false).

Operator Description Example
== Equal to (value) 10 == "10" // true
!= Not equal to (value) 10 != 5 // true
=== Strictly equal to (value and type) 10 === "10" // false
!== Strictly not equal to (value and type) 10 !== "10" // true
> Greater than 10 > 5 // true
< Less than 10 < 5 // false
>= Greater than or equal to 10 >= 10 // true
<= Less than or equal to 10 <= 5 // false

It is generally recommended to use the strict equality operators (=== and !==) to avoid unexpected type coercion issues.

Logical Operators

These operators are used to combine conditional statements or values, returning either true or false.

Operator Description Example
&& Logical AND (age > 18) && (hasLicense === true) // true if both are true
|| Logical OR (isWeekend || isHoliday) // true if at least one is true
! Logical NOT !isLoggedIn // true if isLoggedIn is false

String Operators

The primary string operator is the concatenation operator.

Operator Description Example
+ Concatenates (joins) two strings let greeting = "Hello" + " " + "World!"; // greeting is "Hello World!"

The + operator can also be used with other data types, where JavaScript will attempt to convert them to strings before concatenating. For example:

let message = "Your score is: " + 100; // message is "Your score is: 100"

Type Conversion Operators

While not always explicit operators, JavaScript has several ways to convert between data types.

For more advanced type conversion, refer to the JavaScript Type Conversion Reference.

Other Operators

JavaScript also includes several other useful operators:

You can find detailed explanations of these in the Operator Precedence and Associativity guide.

Understanding and effectively using JavaScript operators is fundamental to writing powerful and dynamic web applications. Experiment with these operators in your code to solidify your understanding.