JavaScript Operators
Operators in JavaScript are used to perform operations on variables and values. From simple arithmetic to logical comparisons, operators are essential for writing functional and expressive code.
JavaScript provides several categories of operators:
Operator Type | Description |
---|---|
Arithmetic Operators | Operators used for basic arithmetic operations like addition, subtraction, etc. Ex: 5 + 3 (Addition) |
Assignment Operators | Operators used to assign values to variables. Ex: x = 10 (Assignment) |
Comparison Operators | Operators used to compare two values, returning true or false. Ex: 5 == 5 (Equality) |
Logical Operators | Operators used to combine multiple boolean expressions. Ex: true && false (AND) |
Unary Operators | Operators that operate on a single operand to produce a result. Ex: ++ (Increment), -- (Decrement) |
Conditional (Ternary) Operator | A shorthand way to write an if-else condition. Ex: condition ? true : false (Ternary) |
1. Arithmetic Operators
Arithmetic operators in JavaScript are used to perform basic mathematical operations such as addition, subtraction, multiplication, and division. These operators are fundamental when working with numeric values in your programs.
The basic arithmetic operators are:
Operator | Description |
---|---|
+ | Addition (adds two values). Ex: 5 + 3 = 8 |
- | Subtraction (subtracts second value from first). Ex: 5 - 3 = 2 |
* | Multiplication (multiplies two values). Ex: 5 * 3 = 15 |
/ | Division (divides the first value by the second). Ex: 5 / 3 = 1.666 |
% | Modulus (returns the remainder of division). Ex: 5 % 3 = 2 |
** | Exponentiation (raises first value to the power of second). Ex: 5 ** 3 = 125 |
Example:
// Arithmetic Operators in JavaScript
let a = 5;
let b = 3;
// 1. Addition (+)
console.log('Addition (5 + 3) =', a + b);
// 2. Subtraction (-)
console.log('Subtraction (5 - 3) =', a - b);
// 3. Multiplication (*)
console.log('Multiplication (5 * 3) =', a * b);
// 4. Division (/)
console.log('Division (5 / 3) =', a / b);
// 5. Modulus (%)
console.log('Modulus (5 % 3) =', a % b);
// 6. Exponentiation (**)
console.log('Exponentiation (5 ** 3) =', a ** b);
// Arithmetic Operators in JavaScript
let a = 5;
let b = 3;
// 1. Addition (+)
console.log('Addition (5 + 3) =', a + b);
// 2. Subtraction (-)
console.log('Subtraction (5 - 3) =', a - b);
// 3. Multiplication (*)
console.log('Multiplication (5 * 3) =', a * b);
// 4. Division (/)
console.log('Division (5 / 3) =', a / b);
// 5. Modulus (%)
console.log('Modulus (5 % 3) =', a % b);
// 6. Exponentiation (**)
console.log('Exponentiation (5 ** 3) =', a ** b);
Output
Addition (5 + 3) = 8
Subtraction (5 - 3) = 2
Multiplication (5 * 3) = 15
Division (5 / 3) = 1.6666666666666667
Modulus (5 % 3) = 2
Exponentiation (5 ** 3) = 125
Addition (5 + 3) = 8
Subtraction (5 - 3) = 2
Multiplication (5 * 3) = 15
Division (5 / 3) = 1.6666666666666667
Modulus (5 % 3) = 2
Exponentiation (5 ** 3) = 125
2. Assignment Operators
Assignment operators in JavaScript are used to assign values to variables. The most basic is the = operator, but JavaScript also supports compound assignment operators that combine arithmetic with assignment for cleaner code.
Common assignment operators include:
Operator | Description |
---|---|
= | Assigns the value on the right to the variable on the left. Ex: x = 10 |
+= | Adds and assigns. Ex: x += 5 (same as x = x + 5) |
-= | Subtracts and assigns. Ex: x -= 3 (same as x = x - 3) |
*= | Multiplies and assigns. Ex: x *= 2 (same as x = x * 2) |
/= | Divides and assigns. Ex: x /= 2 (same as x = x / 2) |
%= | Calculates remainder and assigns. Ex: x %= 4 (same as x = x % 4) |
**= | Exponentiates and assigns. Ex: x **= 3 (same as x = x ** 3) |
Example:
// Assignment Operators in JavaScript
// Basic assignment
let x = 10;
console.log('x = ',x);
// Addition assignment
let a = 10;
a += 5;
console.log('After a += 5:', a);
// Subtraction assignment
let b = 10;
b -= 3;
console.log('After b -= 3:', b);
// Multiplication assignment
let c = 10;
c *= 2;
console.log('After c *= 2:', c);
// Division assignment
let d = 10;
d /= 4;
console.log('After d /= 4:', d);
// Modulus assignment
let e = 10;
e %= 3;
console.log('After e %= 3:', e);
// Exponentiation assignment
let f = 10;
f **= 2;
console.log('After f **= 2:', f);
// Assignment Operators in JavaScript
// Basic assignment
let x = 10;
console.log('x = ',x);
// Addition assignment
let a = 10;
a += 5;
console.log('After a += 5:', a);
// Subtraction assignment
let b = 10;
b -= 3;
console.log('After b -= 3:', b);
// Multiplication assignment
let c = 10;
c *= 2;
console.log('After c *= 2:', c);
// Division assignment
let d = 10;
d /= 4;
console.log('After d /= 4:', d);
// Modulus assignment
let e = 10;
e %= 3;
console.log('After e %= 3:', e);
// Exponentiation assignment
let f = 10;
f **= 2;
console.log('After f **= 2:', f);
Output
x = 10
After a += 5: 15
After b -= 3: 7
After c *= 2: 20
After d /= 4: 2.5
After e %= 3: 1
After f **= 2: 100
x = 10
After a += 5: 15
After b -= 3: 7
After c *= 2: 20
After d /= 4: 2.5
After e %= 3: 1
After f **= 2: 100
3. Comparison Operators
Comparison operators in JavaScript are used to compare two values. These operators return a Boolean value — either true or false — depending on the result of the comparison. They are essential in decision-making and control flow (e.g., in if statements).
Common comparison operators include:
Operator | Example | Description |
---|---|---|
== | 5 == '5' | Equality (compares values, allows type coercion) |
=== | 5 === '5' | Strict equality (compares values and types) |
!= | 5 != '5' | Inequality (not equal, allows type coercion) |
!== | 5 !== '5' | Strict inequality (not equal value or type) |
> | 5 > 3 | Greater than |
< | 5 < 3 | Less than |
>= | 5 >= 5 | Greater than or equal to |
<= | 5 <= 3 | Less than or equal to |
In JavaScript, there are two ways to compare values: == and ===. The == operator is called the loose equality operator. It checks if two values are the same, but it ignores their types. For example, if you compare a number with a string that has the same value, it will say they're equal. On the other hand, the === operator is called the strict equality operator. It checks if both the value and the type are exactly the same. This means that 5 and "5" are not equal when using === because one is a number and the other is a string.
Example:
// Comparison Operators in JavaScript
let a = 5;
let b = '5';
let c = 3;
console.log('a == b:', a == b); // true (value equality, type coerced)
console.log('a === b:', a === b); // false (strict equality)
console.log('a != b:', a != b); // false
console.log('a !== b:', a !== b); // true
console.log('a > c:', a > c); // true
console.log('a < c:', a < c); // false
console.log('a >= 5:', a >= 5); // true
console.log('a <= 3:', a <= 3); // false
// Comparison Operators in JavaScript
let a = 5;
let b = '5';
let c = 3;
console.log('a == b:', a == b); // true (value equality, type coerced)
console.log('a === b:', a === b); // false (strict equality)
console.log('a != b:', a != b); // false
console.log('a !== b:', a !== b); // true
console.log('a > c:', a > c); // true
console.log('a < c:', a < c); // false
console.log('a >= 5:', a >= 5); // true
console.log('a <= 3:', a <= 3); // false
Output
a == b: true
a === b: false
a != b: false
a !== b: true
a > c: true
a < c: false
a >= 5: true
a <= 3: false
a == b: true
a === b: false
a != b: false
a !== b: true
a > c: true
a < c: false
a >= 5: true
a <= 3: false
4. Logical Operators
Logical operators in JavaScript are used to combine or invert boolean values. These are especially useful in conditional statements where you want to test multiple expressions at once.
The main logical operators are:
Operator | Example | Description |
---|---|---|
&& | true && false | Logical AND (returns true if both operands are true) |
|| | true || false | Logical OR (returns true if at least one operand is true) |
! | !true | Logical NOT (inverts the boolean value) |
Example:
// Logical Operators in JavaScript
let a = true;
let b = false;
console.log('a && b:', a && b); // false
console.log('a || b:', a || b); // true
console.log('!a:', !a); // false
console.log('!b:', !b); // true
// Combining comparisons
let age = 20;
console.log('(age > 18 && age < 30):', (age > 18 && age < 30)); // true
console.log('(age < 18 || age > 60):', (age < 18 || age > 60)); // false
// Logical Operators in JavaScript
let a = true;
let b = false;
console.log('a && b:', a && b); // false
console.log('a || b:', a || b); // true
console.log('!a:', !a); // false
console.log('!b:', !b); // true
// Combining comparisons
let age = 20;
console.log('(age > 18 && age < 30):', (age > 18 && age < 30)); // true
console.log('(age < 18 || age > 60):', (age < 18 || age > 60)); // false
Output
a && b: false
a || b: true
!a: false
!b: true
(age > 18 && age < 30): true
(age < 18 || age > 60): false
a && b: false
a || b: true
!a: false
!b: true
(age > 18 && age < 30): true
(age < 18 || age > 60): false
5. Unary Operators
Unary operators are used to perform operations on a single operand (value). They are commonly used to increment or decrement a value, change the sign of a number, convert a value to its boolean equivalent, or determine the type of a value.
The basic unary operators are:
Operator | Description |
---|---|
++ | Increment (increases the value by 1). Ex: let a = 5; a++ // 6 |
-- | Decrement (decreases the value by 1). Ex: let a = 5; a-- // 4 |
+ | Unary Plus (converts a value to a number). Ex: let a = '5'; let b = +a; // 5 |
- | Unary Negation (converts a value to a number and negates it). Ex: let a = 5; let b = -a; // -5 |
! | Logical NOT (inverts the boolean value). Ex: let a = true; let b = !a; // false |
~ | Bitwise NOT (inverts the bits of a number). Ex: let a = 5; let b = ~a; // -6 |
typeof | Returns the type of a value. Ex: let a = 5; let b = typeof a; // "number" |
void | Evaluates an expression and returns undefined. Ex: let result = void (5 + 3); // undefined |
delete | Removes a property from an object. Ex: let obj = { x: 10 }; delete obj.x; // true |
Example:
// Unary Operators in JavaScript
let a = 5;
let b;
// Increment (++)
a++;
console.log(a); // 6 (Increases the value of 'a' by 1)
// Decrement (--)
a--;
console.log(a); // 5 (Decreases the value of 'a' by 1)
// Unary Plus (+)
// If the string represents a valid number, it converts it to that number (e.g., '5' becomes 5).
// If the string represents a non-numeric value (like 'abc'), it converts it to NaN (Not-a-Number).
// If the operand is already a number, it doesn't change it.
b = '5';
b = +b;
console.log(b); // 5 (Converts the string '5' to number 5)
// Unary Negation (-)
// If the string represents a valid number, it converts it to that number and negates it (e.g., '5' becomes -5).
// If the string represents a non-numeric value (like 'hello'), it converts it to NaN (Not-a-Number), and negating NaN still results in NaN.
// If the operand is already a number, it simply negates it (e.g., 10 becomes -10).
b = -a;
console.log(b); // -5 (Converts 'a' to number and negates it)
// Logical NOT (!)
b = !a;
console.log(b); // false (Inverts the boolean value of 'a', so true becomes false)
// Bitwise NOT (~)
b = ~a;
console.log(b); // -6 (Inverts all bits of 'a'. 5 in binary is 0101, so ~a becomes -6)
// typeof
console.log(typeof a); // "number" (Returns the type of 'a', which is a number)
// void
let result = void (5 + 3); // Evaluates (5 + 3), but 'void' returns 'undefined'
console.log(result); // undefined (void ensures that no value is returned)
// delete
let obj = { name: "Alice" };
delete obj.name;
console.log(obj); // {} (Removes the 'name' property from the object)
// Unary Operators in JavaScript
let a = 5;
let b;
// Increment (++)
a++;
console.log(a); // 6 (Increases the value of 'a' by 1)
// Decrement (--)
a--;
console.log(a); // 5 (Decreases the value of 'a' by 1)
// Unary Plus (+)
// If the string represents a valid number, it converts it to that number (e.g., '5' becomes 5).
// If the string represents a non-numeric value (like 'abc'), it converts it to NaN (Not-a-Number).
// If the operand is already a number, it doesn't change it.
b = '5';
b = +b;
console.log(b); // 5 (Converts the string '5' to number 5)
// Unary Negation (-)
// If the string represents a valid number, it converts it to that number and negates it (e.g., '5' becomes -5).
// If the string represents a non-numeric value (like 'hello'), it converts it to NaN (Not-a-Number), and negating NaN still results in NaN.
// If the operand is already a number, it simply negates it (e.g., 10 becomes -10).
b = -a;
console.log(b); // -5 (Converts 'a' to number and negates it)
// Logical NOT (!)
b = !a;
console.log(b); // false (Inverts the boolean value of 'a', so true becomes false)
// Bitwise NOT (~)
b = ~a;
console.log(b); // -6 (Inverts all bits of 'a'. 5 in binary is 0101, so ~a becomes -6)
// typeof
console.log(typeof a); // "number" (Returns the type of 'a', which is a number)
// void
let result = void (5 + 3); // Evaluates (5 + 3), but 'void' returns 'undefined'
console.log(result); // undefined (void ensures that no value is returned)
// delete
let obj = { name: "Alice" };
delete obj.name;
console.log(obj); // {} (Removes the 'name' property from the object)
Output
6
5
5
-5
false
-6
"number"
undefined
{}
6
5
5
-5
false
-6
"number"
undefined
{}
6. Ternary Operator
The ternary operator is a shorthand way of writing an `if-else` statement. It's called "ternary" because it operates on three operands: a condition, a result for `true`, and a result for `false`.
The syntax of the ternary operator is:
Operator | Example | Explanation |
---|---|---|
condition ? value_if_true : value_if_false | let result = (5 > 3) ? 'Yes' : 'No'; | Evaluates the condition: if true, returns the first value; if false, returns the second value. |
Example:
// Ternary Operator in JavaScript
let age = 20;
// Using the ternary operator to check if the person is an adult
let result = (age >= 18) ? 'Adult' : 'Minor';
console.log(result); // Output: "Adult"
// Ternary Operator in JavaScript
let age = 20;
// Using the ternary operator to check if the person is an adult
let result = (age >= 18) ? 'Adult' : 'Minor';
console.log(result); // Output: "Adult"
Output
Adult
Adult
Explanation:
In the example above, the condition (age >= 18) is checked. Since age is 20, which is greater than or equal to 18, the result is `"Adult"`. If the condition was false (e.g., if age was 16), the result would be `"Minor"`.
Why use the Ternary Operator?
The ternary operator is very useful for writing compact and clean code, especially when you need to assign values based on simple conditions. Instead of using a full `if-else` statement, you can do it in a single line!
Frequently Asked Questions
What are operators in JavaScript?
What are operators in JavaScript?
Operators in JavaScript are special symbols or keywords used to perform operations on values and variables. They include arithmetic, assignment, comparison, logical, bitwise, unary, and ternary operators.
What are arithmetic operators in JavaScript?
What are arithmetic operators in JavaScript?
Arithmetic operators perform mathematical operations such as +, -, *, /, %, and **.
What is the difference between == and === in JavaScript?
What is the difference between == and === in JavaScript?
The == operator checks for value equality after type coercion, while === checks for both value and type equality without converting data types.
What are logical operators in JavaScript?
What are logical operators in JavaScript?
Logical operators are used to combine multiple conditions. These include && (AND), || (OR), and ! (NOT). They return boolean values based on the logic between expressions.
What is the ternary operator in JavaScript?
What is the ternary operator in JavaScript?
The ternary operator is a shorthand for if-else statements. It uses the syntax: condition ? expr1 : expr2, returning one of two expressions based on the condition.
Now that you’ve learned about JavaScript operators, it’s time to dive into comments. Comments are an essential tool for documenting your code and making it more readable.