JavaScript operators are symbols used to perform operations on values or variables. There are several types of operators available in JavaScript, including assignment, arithmetic, comparison, and logical operators. By understanding these operators and how to use them, you can write more powerful and efficient JavaScript code.
Types of operators in JavaScript:
Assignment Operators
The assignment operator (=
) is used to assign a value to a variable. For example:
var x = 5;
This assigns the value 5
to the variable x
.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations on values. The following arithmetic operators are available in JavaScript:
- Addition (
+
): Adds two values together. For example:3 + 4
. - Subtraction (
-
): Subtracts one value from another. For example:6 - 2
. - Multiplication (
*
): Multiplies two values together. For example:5 * 7
. - Division (
/
): Divides one value by another. For example:10 / 2
. - Modulus (
%
): Returns the remainder of a division operation. For example:11 % 3
would return2
.
Comparison Operators
Comparison operators are used to compare two values and return a Boolean value (true
or false
). The following comparison operators are available in JavaScript:
- Equal to (
==
): Compares two values for equality. For example:3 == 3
would returntrue
. - Not equal to (
!=
): Compares two values for inequality. For example:3 != 4
would returntrue
. - Greater than (
>
): Compares two values to see if the first value is greater than the second value. For example:5 > 3
would returntrue
. - Less than (
<
): Compares two values to see if the first value is less than the second value. For example:2 < 7
would returntrue
. - Greater than or equal to (
>=
): Compares two values to see if the first value is greater than or equal to the second value. For example:6 >= 6
would returntrue
. - Less than or equal to (
<=
): Compares two values to see if the first value is less than or equal to the second value. For example:4 <= 5
would returntrue
.
Logical Operators
Logical operators are used to combine two or more conditions and return a Boolean value. The following logical operators are available in JavaScript:
- AND (
&&
): Returnstrue
if both conditions are true. For example:(3 < 5) && (6 > 4)
would returntrue
. - OR (
||
): Returnstrue
if at least one of the conditions is true. For example:(3 > 5) || (6 > 4)
would returntrue
. - NOT (
!
): Returns the opposite of a Boolean value. For example:!(3 > 5)
would returntrue
.