Operators
What are Operators?β
Operators are symbols that perform actions on values. Think of them as the verbs in your codeβthey tell JavaScript what to do with your data.
Real-World Analogy π§β
Operators are like tools in a toolbox:
+is like glue (joins things together)-is like scissors (removes/subtracts)*is like a photocopier (multiplies copies)==is like a scale (compares if things are equal)
// Using operators
const x = 10; // = operator (assignment)
const y = x + 5; // + operator (addition)
const isEqual = x == 10; // == operator (comparison)
Learning Path for Operators π―β
π’ Essential (Learn These First!)β
Start with these if you're a beginner:
- β
Arithmetic operators:
+,-,*,/,% - β
Assignment operators:
=,+=,-= - β
Comparison operators:
==,===,>,< - β
Logical operators:
&&,||,!
π‘ Intermediate (Learn After Basics)β
These are very useful once you're comfortable:
- π Ternary operator:
?:(shorthand if/else) - π Typeof operator:
typeof(check data types)
π΄ Advanced (Learn Later)β
Skip these for now if you're just starting:
- πΈ Optional chaining:
?. - πΈ Nullish coalescing:
?? - πΈ Spread operator:
... - πΈ Delete operator:
delete - πΈ In operator:
in - πΈ Operator precedence
Start with sections 1-4 (Arithmetic, Assignment, Comparison, Logical). These cover 95% of what you'll use daily!
Once you're comfortable with the basics, come back for the intermediate and advanced operators. Don't feel pressured to learn everything at onceβJavaScript has many operators, but you'll naturally learn them as you need them.
π’ Essential Operators (Learn These First!)
These are the operators you'll use every single day. Master these before moving on!
Arithmetic Operators - Math Operations βββοΈββ
These operators perform mathematical calculations, just like a calculator!
Basic Math Operatorsβ
const x = 20;
const y = 6;
console.log(x + y); // 26 (Addition - add numbers together)
console.log(x - y); // 14 (Subtraction - subtract one from another)
console.log(x * y); // 120 (Multiplication - multiply numbers)
console.log(x / y); // 3.333... (Division - divide numbers)
console.log(x % y); // 2 (Modulo - remainder after division)
Real-World Examples πβ
// Calculate total price
const itemPrice = 25;
const quantity = 3;
const totalPrice = itemPrice * quantity;
console.log(totalPrice); // 75
// Calculate change
const paid = 100;
const cost = 75;
const change = paid - cost;
console.log(change); // 25
// Split a bill equally
const billTotal = 120;
const people = 4;
const perPerson = billTotal / people;
console.log(perPerson); // 30
The Modulo Operator (%) Explained πβ
The modulo (%) gives you the remainder after division. It's super useful!
// Check if a number is even or odd
const number = 7;
const remainder = number % 2;
if (remainder === 0) {
console.log("Even");
} else {
console.log("Odd"); // Output: Odd (because 7 Γ· 2 = 3 remainder 1)
}
// Cycle through values (like a clock)
const hours = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
let currentHour = 10;
currentHour = (currentHour + 5) % 12; // 10 + 5 = 15, 15 % 12 = 3
console.log(currentHour); // 3 (3 PM)
Visual Explanation:
10 % 3 = 1 because 10 Γ· 3 = 3 with remainder 1
15 % 4 = 3 because 15 Γ· 4 = 3 with remainder 3
20 % 5 = 0 because 20 Γ· 5 = 4 with remainder 0
+- Combining, adding, totaling-- Removing, calculating difference, change*- Scaling, multiplying quantities/- Splitting, averaging, dividing%- Checking even/odd, cycling values, patterns
Assignment Operatorβ
You will be using the assignment operator = to assign a value to a variable. For example:
let x = 10;
x = 15;
It assigns the value 10 to the variable x, and then re-assigned 15. However, there are other assignment operators that you can use to assign a value to a variable. For example:
Don't worry if you don't understand the code below. Just remember that you can use these operators to assign a value to a variable.
It's up to you if you want to use these operators or not. You can use the assignment operator = to assign a value to a variable, and it's fine.
let x = 10;
x = 20; // Assigns the value 20 to x
x += 10; // Adds 10 to x and assigns the result to x
x -= 5; // Subtracts 5 from x and assigns the result to x
x *= 2; // Multiplies x by 2 and assigns the result to x
x /= 2; // Divides x by 2 and assigns the result to x
Ignore &&=, ||=, and ??= operators for now if you are a beginner. It's a bit advanced topic. You can come back to this section later.
In ES12, Logical Assignment Operators were introduced. These operators perform logical operations on the variable and the value and then assign the result to the variable. For example:
let x = 10;
x &&= 5; // Assigns 5 to x if x is truthy
x ||= 5; // Assigns 5 to x if x is falsy
x ??= 5; // Assigns 5 to x if x is null or undefined
x &&= 5 is equivalent to x = x && 5, and same for x ||= 5 β x = x || 5, and x ??= 5 β x = x ?? 5.
&&= operatorβ
Let's take a look at the following example:
const object = {
name: "Rizwan",
age: 20,
};
object.name &&= "Ashiq"; // equivalent to object.name = object.name && "Ashiq"
console.log(object.name); // Output: Ashiq
Here, the logical AND assignment operator &&= is used to assign the value "Ashiq" to the name property of the object if the name property is truthy. Since "Rizwan" is truthy, the value "Ashiq" is assigned to the name property.
||= operatorβ
const object = {
name: "Rizwan",
age: 20,
};
object.name ||= "Ashiq"; // equivalent to object.name = object.name || "Ashiq"
console.log(object.name); // Output: Rizwan
Here, the logical OR assignment operator ||= is used to assign the value "Ashiq" to the name property of the object if the name property is falsy. Since "Rizwan" is truthy, the assignment is skipped and name remains "Rizwan".
??= operatorβ
const object = {
name: "Rizwan",
age: 20,
};
object.name ??= "Ashiq"; // equivalent to object.name = object.name ?? "Ashiq"
console.log(object.name); // Output: Rizwan
Here, the nullish coalescing assignment operator ??= is used to assign the value "Ashiq" to the name property of the object if the name property is null or undefined. Since "Rizwan" is neither null nor undefined, the assignment is skipped and name remains "Rizwan".
Comparison Operators - Asking Questions ββ
Comparison operators compare two values and return true or false. Think of them as asking yes/no questions about your data.
Basic Comparisonsβ
const age = 20;
console.log(age > 18); // true (Is 20 greater than 18? Yes!)
console.log(age < 18); // false (Is 20 less than 18? No!)
console.log(age >= 20); // true (Is 20 greater than or equal to 20? Yes!)
console.log(age <= 18); // false (Is 20 less than or equal to 18? No!)
Real-World Examples πβ
// Age verification
const userAge = 16;
const canDrive = userAge >= 18;
console.log(canDrive); // false
// Price comparison
const budget = 100;
const itemPrice = 75;
const canAfford = itemPrice <= budget;
console.log(canAfford); // true
// Score checker
const score = 85;
const passed = score >= 60;
console.log(passed); // true
Equality: == vs === (VERY Important! β οΈ)β
JavaScript has two ways to check equality, and they're NOT the same!
β == (Loose Equality - Avoid This!)β
The == operator converts types before comparing (type coercion):
console.log(5 == "5"); // true π (converts "5" to number 5)
console.log(0 == false); // true π (converts false to 0)
console.log(null == undefined); // true π (treats as similar)
console.log(" " == 0); // true π (empty string becomes 0)
This is confusing and causes bugs! β
β
=== (Strict Equality - Use This!)β
The === operator checks both value AND type (no conversion):
console.log(5 === "5"); // false β
(different types: number vs string)
console.log(5 === 5); // true β
(same value AND type)
console.log(0 === false); // false β
(different types)
console.log(" " === 0); // false β
(different types)
Visual Comparison:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Loose (==) vs Strict (===) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β 5 == "5" β true vs 5 === "5" β false β
β 0 == false β true vs 0 === false β false β
β "" == 0 β true vs "" === 0 β false β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
=== and !==Modern JavaScript Best Practice:
// β DON'T use loose equality
if (value == 5) { }
if (value != "hello") { }
// β
DO use strict equality
if (value === 5) { }
if (value !== "hello") { }
Why? === prevents unexpected bugs from type coercion!
// Bug example with ==
const userInput = "0"; // User entered "0" (string)
if (userInput == 0) {
console.log("Input is zero"); // β Runs! But "0" is not actually 0
}
// Fixed with ===
if (userInput === 0) {
console.log("Input is zero"); // β
Doesn't run (correct!)
}
Complete Comparison Referenceβ
| Operator | Meaning | Example | Result |
|---|---|---|---|
> | Greater than | 10 > 5 | true |
< | Less than | 10 < 5 | false |
>= | Greater than or equal | 10 >= 10 | true |
<= | Less than or equal | 10 <= 5 | false |
=== | Strict equal | 10 === 10 | true |
!== | Strict not equal | 10 !== 5 | true |
== | Loose equal (avoid!) | 10 == "10" | true π |
!= | Loose not equal (avoid!) | 10 != "5" | true π |
- Use
===for equality (not==) - Use
!==for inequality (not!=) - This prevents 99% of comparison bugs!
Comparing Objectsβ
What if we want to compare two objects? For example:
const object1 = {
name: "Rizwan",
age: 20,
};
const object2 = {
name: "Rizwan",
age: 20,
};
console.log(object1 === object2); // Output: false
const object3 = object1;
console.log(object1 === object3); // Output: true
In the above example, object1 === object2 returns false even though both objects have identical properties β because objects are compared by reference, not by value. object1 and object2 are two separate objects in memory. object3 points to the same object as object1, so they share the same reference and the comparison returns true.
Logical Operatorβ
Logical operators are symbols or keywords that perform logical operations on one or more Boolean (true/false) values or expressions. Types of logical operators include:
AND operator:β
The && operator returns true if both operands are true, otherwise it returns false.
const a = true;
const b = false;
console.log(a && b); // Output: false
console.log(true && true); // Output: true
OR operator:β
The || operator returns true if at least one operand is true, otherwise it returns false.
const a = true;
const b = false;
console.log(a || b); // Output: true
console.log(false || false); // Output: false
NOT operator:β
The ! operator flips the boolean value β true becomes false, and false becomes true.
const a = true;
console.log(!a); // Output: false
console.log(!false); // Output: true
Short-Circuit Evaluation β‘β
Logical operators don't always evaluate both sides. JavaScript stops as soon as the result is determined:
&&stops at the first falsy value and returns it; if all are truthy, returns the last value.||stops at the first truthy value and returns it; if all are falsy, returns the last value.
// && short-circuits on the first falsy value
console.log(false && someExpression); // false β someExpression is never evaluated
// || short-circuits on the first truthy value
console.log(true || someExpression); // true β someExpression is never evaluated
// Practical use: default values
const username = null;
const displayName = username || "Guest"; // "Guest" (because username is falsy)
// Practical use: guard before calling a method
const user = null;
const name = user && user.getName(); // null β avoids "Cannot read property" error
Ternary Operator (?)β
The ternary operator ? is used to perform conditional operations. It takes three operands: a condition followed by a question mark ?, then an expression to execute if the condition is truthy followed by a colon :, and finally the expression to execute if the condition is falsy. For example:
const x = 10;
const result = x > 5 ? "x is greater than 5" : "x is less than or equal to 5";
console.log(result); // Output: x is greater than 5
Optional Chaining Operator (?.)β
Working with objects in JavaScript can be tricky. If you try to access a nested property of an object that does not exist, it throws an error. For example:
const person = {
name: "Rizwan",
};
console.log(person.name); // Output: Rizwan
console.log(person.age); // Output: undefined
console.log(person.address.city); // Output: Uncaught TypeError: Cannot read property 'city' of undefined
Did you notice that the person.name didn't throw an error, but person.address.city did?
Because accessing nested properties (like person.address.city) throws an error if any intermediate property (in this case, address) is undefined. Accessing a non-existing property directly (like person.age) returns undefined without throwing an error.
Developers have been using the && operator to avoid this error. For example:
const person = {
name: "Rizwan",
};
console.log(person.name); // Output: Rizwan
console.log(person.age); // Output: undefined
console.log(person.address && person.address.city); // Output: undefined
But, this is not a good solution. The && operator checks if the left-hand side operand is truthy or falsy. If the left-hand side operand is truthy, it returns the right-hand side operand. If the left-hand side operand is falsy, it returns the left-hand side operand. So, using the && operator is not a good solution to avoid the error.
The optional chaining operator ?. is also used to avoid this error.
Both ?. and && do the same thing, the short-circuiting. But, ?. is more readable and less error-prone.
For example:
const person = {
name: "Rizwan",
};
console.log(person.name); // Output: Rizwan
console.log(person.age); // Output: undefined
console.log(person.address?.city); // Output: undefined
Here, if the address property is undefined, the optional chaining operator ?. returns undefined and does not go further to access the city property, avoiding the error.
Nullish Coalescing Operator (??)β
The nullish coalescing operator ?? is used to return the right-hand side operand if the left-hand side operand is null or undefined, otherwise it returns the left-hand side operand. For example:
const x = null;
const y = 10;
console.log(x ?? y); // Output: 10
Here, x is null, so the right-hand side operand y is returned.
const x = 0;
const y = 10;
console.log(x ?? y); // Output: 0
Here, x is 0, so the left-hand side operand x is returned.
Sometimes I use the ?? operator instead of the ternary operator ? when I am assigning a value to a variable by checking if the variable is null or undefined. For example:
const x = null;
const result1 = x ?? 10;
// is equivalent to
const result2 = (x !== null && x !== undefined) ? x : 10;
console.log(result1); // 10
console.log(result2); // 10
The ?? operator is more readable and less error-prone.
typeof Operatorβ
The typeof operator is a unary operator that returns a string indicating the type of the variable or an expression. It has the following syntax:
typeof variable_or_expression;
// For example:
typeof "Hello, world!"; // returns 'string'
Here are a few examples of the typeof operator:
typeof "Hello, world!"; // returns 'string'
typeof 42; // returns 'number'
typeof true; // returns 'boolean'
typeof null; // returns 'object'
typeof undefined; // returns 'undefined'
typeof {}; // returns 'object'
typeof []; // returns 'object'
typeof function () {}; // returns 'function'
In some cases, the typeof operator may not return the expected result. For example, the typeof operator returns 'object' for arrays, even though they are not objects in the traditional sense. To check if a variable is an array, you can use the Array.isArray() method, like this:
typeof []; // returns 'object'
Array.isArray([]); // returns true
The typeof operator is useful for checking the type of value before operating on it. For example:
function add(x, y) {
if (typeof x !== "number" || typeof y !== "number") {
throw new Error("Invalid argument");
}
return x + y;
}
In this example, the add() function checks the type of its arguments before performing the addition. If either of the arguments is not a number, it throws an error.
delete Operatorβ
The delete operator is a unary operator that deletes a property from an object or an element from an array. It has the following syntax:
delete object.property; // delete a property
delete object["property"]; // delete a property
delete array[index]; // delete an element from an array by index (starting from 0)
The delete operator returns true if the property was successfully deleted, and false if the property could not be deleted. Let's look in detail at how the delete operator works.
Deleting properties from an objectβ
The delete operator can be used to delete properties from an object. For example:
const obj = { x: 1, y: 2 };
delete obj.x; // returns true
console.log(obj); // { y: 2 }
Deleting elements from an arrayβ
The delete operator can be used to delete elements from an array. For example:
const arr = [1, 2, 3];
delete arr[1]; // returns true
console.log(arr); // [1, empty, 3]
console.log(arr.length); // 3
In the example above, the delete operator deletes the element at index 1, but the array length remains unchanged. This is because the delete operator does not change the length of an array. To remove an element from an array and change the length of the array, you can use the Array.prototype.splice() method:
const arr = [1, 2, 3];
arr.splice(1, 1); // returns [2]
console.log(arr); // [1, 3]
console.log(arr.length); // 2
Spread Operatorβ
The spread operator ... is used to expand an iterable object into the list of arguments. For example:
const arr = [1, 2, 3];
console.log(...arr); // Output: 1 2 3
Here, the spread operator ... expands the array into the list of arguments. The console.log() function then prints the list of arguments to the console.
It can also merge two or more arrays. For example:
const arr = [1, 2, 3];
const anotherArr = [4, 5, 6, ...arr];
console.log(anotherArr); // Output: [4, 5, 6, 1, 2, 3]
It can do the same with objects. For example:
const obj1 = { x: 1, y: 2 };
const obj2 = { z: 3 };
const obj3 = { ...obj1, ...obj2 };
console.log(obj3); // Output: { x: 1, y: 2, z: 3 }
in Operatorβ
The in operator is used to check if a property exists in an object. It returns true if the property exists, and false if the property does not exist. For example:
const obj = { x: 1, y: 2 };
console.log("x" in obj); // Output: true
console.log("z" in obj); // Output: false
Operator Precedenceβ
Operator precedence determines the order in which operators are evaluated. Operators with higher precedence are evaluated first. For example:
const x = 10;
const y = 20;
const z = 30;
const result = x + y * z;
console.log(result); // Output: 610
10 + 20 * 30
β ββ 1 ββ
ββββ 2 ββββββ
Here, the multiplication operator * has higher precedence than the addition operator +, so it is evaluated first (20 * 30 = 600), then the result is added to x (10 + 600 = 610). JavaScript has a precedence table that lists all operators in order of precedence.
When operators share the same precedence level (like * and /), they are evaluated left to right:
1 + 8 * 4 / 5
β βββ 1 βββ
β βββ 2 βββ
ββββ 3 ββββββ
(1 + ( (2 ** 3) * 4 / 5) )
β β ββ 1 ββ β β
β βββββββ 2 ββββββββ β
βββββββββββ 3 βββββββββββ
Table for precedence of operators in JavaScript (from highest to lowest precedence):
| Operator | Description | Example |
|---|---|---|
() | Grouping | (1 + 2) * 3 |
[] | Element access | arr[0] |
. | Member access | obj.prop |
new | Instantiation | new Foo() |
++ -- | Increment/decrement | ++x y-- |
** | Exponentiation | x ** y |
! ~ + - typeof void delete | Unary | !x typeof x delete x.prop |
* / % | Multiplicative | x * y x / y x % y |
+ - | Additive | x + y x - y |
<< >> >>> | Bitwise shift | x << y x >> y x >>> y |
< <= > >= | Relational | x < y x <= y x > y x >= y |
in instanceof | Relational | x in y x instanceof y |
== != === !== | Equality | x == y x != y x === y x !== y |
& | Bitwise AND | x & y |
^ | Bitwise XOR | x ^ y |
| | Bitwise OR | x | y |
&& | Logical AND | x && y |
|| | Logical OR | x || y |
? : | Conditional | x ? y : z |
= += -= *= /= %= **= <<= >>= >>>= &= ^= |= | Assignment | x = y x += y x -= y x |= y |
, | Comma | x, y |
Conclusionβ
In this article, you learned about the operators in JavaScript. You learned about the following operators:
- Arithmetic operators (
+,-,*,/,%,**) - Logical operators (&&, ||, !)
- Assignment operators (
=,+=,-=,*=,/=,%=) - Comparison operators (
==,===,!=,!==,>,<,>=,<=) - Optional chaining operator (
?.) - Nullish coalescing operator (
??) - Conditional (ternary) operator (
?:) - Operator precedence
typeofoperatordeleteoperator