Skip to main content

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:

  1. βœ… Arithmetic operators: +, -, *, /, %
  2. βœ… Assignment operators: =, +=, -=
  3. βœ… Comparison operators: ==, ===, >, <
  4. βœ… Logical operators: &&, ||, !

🟑 Intermediate (Learn After Basics)​

These are very useful once you're comfortable:

  1. πŸ“Œ Ternary operator: ? : (shorthand if/else)
  2. πŸ“Œ Typeof operator: typeof (check data types)

πŸ”΄ Advanced (Learn Later)​

Skip these for now if you're just starting:

  1. πŸ”Έ Optional chaining: ?.
  2. πŸ”Έ Nullish coalescing: ??
  3. πŸ”Έ Spread operator: ...
  4. πŸ”Έ Delete operator: delete
  5. πŸ”Έ In operator: in
  6. πŸ”Έ Operator precedence
For Beginners

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​

Common Arithmetic 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
When to Use Each Operator
  • + - 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:

Example of assignment operator
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:

tip

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.

Other Assignment Operators
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
tip

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
note

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​

Comparing Numbers
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 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
danger
Always Use === 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​

OperatorMeaningExampleResult
>Greater than10 > 5true
<Less than10 < 5false
>=Greater than or equal10 >= 10true
<=Less than or equal10 <= 5false
===Strict equal10 === 10true
!==Strict not equal10 !== 5true
==Loose equal (avoid!)10 == "10"true πŸ˜•
!=Loose not equal (avoid!)10 != "5"true πŸ˜•
Quick Rules
  • 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:

Example of the ternary operator
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:

Accessing Nested Objects Throws Error
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:

With && Operator
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:

With Optional Chaining Operator
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:

Examples of nullish coalescing operator
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.

Examples of nullish coalescing operator
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.

tip

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:

Using ?? operator instead of the ternary operator
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:

Syntax of typeof operator
typeof variable_or_expression;

// For example:
typeof "Hello, world!"; // returns 'string'

Here are a few examples of the typeof operator:

Examples of 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:

Checking if a variable is an array
typeof []; // returns 'object'
Array.isArray([]); // returns true

The typeof operator is useful for checking the type of value before operating on it. For example:

Checking the type of value before operating
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:

Syntax of delete operator
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:

Example of spread operator
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:

Example of spread operator
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:

Example of spread operator
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):

OperatorDescriptionExample
()Grouping(1 + 2) * 3
[]Element accessarr[0]
.Member accessobj.prop
newInstantiationnew Foo()
++ --Increment/decrement++x y--
**Exponentiationx ** y
! ~ + - typeof void deleteUnary!x typeof x delete x.prop
* / %Multiplicativex * y x / y x % y
+ -Additivex + y x - y
<< >> >>>Bitwise shiftx << y x >> y x >>> y
< <= > >=Relationalx < y x <= y x > y x >= y
in instanceofRelationalx in y x instanceof y
== != === !==Equalityx == y x != y x === y x !== y
&Bitwise ANDx & y
^Bitwise XORx ^ y
&#124;Bitwise ORx &#124; y
&&Logical ANDx && y
&#124;&#124;Logical ORx &#124;&#124; y
? :Conditionalx ? y : z
= += -= *= /= %= **= <<= >>= >>>= &= ^= &#124;=Assignmentx = y x += y x -= y x &#124;= y
,Commax, 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
  • typeof operator
  • delete operator