Have you ever wondered how JavaScript performs calculations, makes decisions, or combines strings? Then, congratulations, youāve already encountered JavaScript operatorsāeven if you didnāt realize it! These operators are the key to writing cleaner, more efficient code, no matter your skill level.
In this guide, weāll start with the basics and work our way up to the more advanced JavaScript operators. This tutorial is useful for beginners who start coding, as well as professional developers who want to polish their skills and master JavaScript operators.
Table of Contents
1. Arithmetic Operators: The Foundation of Math š§®
Let’s start from the basics.
Arithmetic operators allow you to make calculations like adding, subtracting, or multiplying.
Basic Arithmetic Operators:
+
(Addition): Adds two numbers together.-
(Subtraction): Subtracts the second number from the first.*
(Multiplication): Multiplies two numbers./
(Division): Divide the first number by the second.%
(Modulus): Returns the remainder of a division.
Example:
let a = 10; let b = 3; console.log(a + b); // 13 (Addition) console.log(a - b); // 7 (Subtraction) console.log(a * b); // 30 (Multiplication) console.log(a / b); // 3.33 (Division) console.log(a % b); // 1 (Modulus)
Pro-Level Tip: ++
and --
- JavaScript also has increment (
++
) and decrement (--
) operators for quickly increasing or decreasing a value by 1.
let x = 5; x++; // Same as x = x + 1 console.log(x); // 6 x--; // Same as x = x - 1 console.log(x); // 5
Note: These operators can be used either as prefix (++x
) or postfix (x++
), depending on whether you want the increment or decrement to happen immediately or after the current line of code.
JavaScript operators Cheat Sheet
2. Assignment Operators: Storing Values š
They are the simplest but also the most commonly used. Theyāre used to assign values to variables. Doesn’t the name of this operator is lightning a bulb in your mind?
Basic Assignment Operator:
=
(Equal): Assigns the value on the right to the variable on the left.
let number = 20; let name = "JavaScript";
Pro-Level Tip: Compound Assignment Operators
You can combine assignment operator with arithmetic operators to shorten your code. These are called compound assignment operators:
+=
(Addition assignment): Adds and then assigns.-=
(Subtraction assignment): Subtracts and then assigns.*=
(Multiplication assignment): Multiplies and then assigns./=
(Division assignment): Divides and then assigns.
let x = 10; x += 5; // Same as x = x + 5 console.log(x); // 15 x *= 2; // Same as x = x * 2 console.log(x); // 30
These operators save time and make your code cleaner!
JavaScript operators Cheat Sheet
3. Comparison Operators: Making Decisions š¤
They are used to compare two values and return a Boolean result: either true
or false
. These are essential when working with if
statements or loops.
Basic Comparison Operators:
==
(Equal to): Checks if two values are equal (loose comparison).===
(Strict equal to): Checks if two values are equal and of the same type (strict comparison).!=
(Not equal to): Checks if two values are not equal.!==
(Strict not equal to): Checks if two values are not equal or not of the same type.
Example:
let x = 5; let y = '5'; console.log(x == y); // true (loose comparison, types ignored) console.log(x === y); // false (strict comparison, types matter) console.log(x != y); // false (values are equal) console.log(x !== y); // true (values are equal, but types are not)
Pro-Level Tip: Always Use ===
for Safety
- Using the strict equality operator (
===
) ensures that youāre not just comparing values but also checking the type, which can prevent errors in larger programs.
JavaScript operators Cheat Sheet
4. Logical Operators: Combining Conditions š§
Logical operators are used to combine multiple conditions in your code. These are critical when youāre writing more complex if
statements.
Logical Operators:
&&
(AND): Returnstrue
if both conditions are true.||
(OR): Returnstrue
if at least one condition is true.!
(NOT): Inverts the result of a condition.
Example:
let age = 25; let hasLicense = true; console.log(age > 18 && hasLicense); // true (both conditions are true) console.log(age > 18 || hasLicense); // true (one or both are true) console.log(!hasLicense); // false (inverts the result)
Pro-Level Tip: Short-Circuit Evaluation
In JavaScript, logical operators are short-circuit, meaning they stop evaluating as soon as the result is clear.
let isLoggedIn = true; let isAdmin = false; if (isLoggedIn || isAdmin) { console.log('Access granted!'); // Prints 'Access granted!' because `isLoggedIn` is true. }
JavaScript operators Cheat Sheet
5. Bitwise Operators: Manipulating Bits āļø
Bitwise operators work with binary data and are used less frequently than arithmetic or comparison operators, but theyāre powerful in certain applications like low-level programming.
Bitwise Operators:
&
(AND): Performs a bitwise AND operation.|
(OR): Performs a bitwise OR operation.^
(XOR): Performs a bitwise exclusive OR operation.~
(NOT): Inverts all the bits in a number.
let a = 5; // In binary: 0101 let b = 3; // In binary: 0011 console.log(a & b); // 1 (binary: 0001) console.log(a | b); // 7 (binary: 0111) console.log(a ^ b); // 6 (binary: 0110) console.log(~a); // -6 (inverts all bits)
Let’s break down what’s happening in each of these console logs:
Scenario 1: console.log(a & b);
a
is 5 (binary: 0101)b
is 3 (binary: 0011)- The
&
operator compares each bit ofa
andb
and returns 1 if both bits are 1. - The result is 1 (binary: 0001) because only the least significant bit is set to 1 in both
a
andb
.
Scenario 2: console.log(a | b);
a
is 5 (binary: 0101)b
is 3 (binary: 0011)- The
|
operator compares each bit ofa
andb
and returns 1 if either bit is 1. - The result is 7 (binary: 0111) because the bits that are set to 1 in either
a
orb
(or both) are set to 1 in the result.
Scenario 3: console.log(a ^ b);
a
is 5 (binary: 0101)b
is 3 (binary: 0011)- The
^
operator compares each bit ofa
andb
and returns 1 if the bits are different. - The result is 6 (binary: 0110) because the bits that are different between
a
andb
are set to 1 in the result.
Scenario 4: console.log(~a);
a
is 5 (binary: 0101)- The
~
operator inverts all the bits ofa
. - The result is -6 (binary: 1010) because the most significant bit is set to 1, indicating a negative number in two’s complement representation.
Bitwise operators are great for optimizing performance or handling binary data, but you wonāt encounter them as much in typical web development.
JavaScript operators Cheat Sheet
6. String Operators: Merging Text Effortlessly š§µ
String operators are mainly used to work with and manipulate strings (text).
Basic String Operator:
+
(Concatenation): Combines two strings into one.
Example:
let firstName = "Areeb"; let lastName = "Anwar"; let fullName = firstName + " " + lastName; console.log(fullName); // Areeb Anwar
JavaScript operators Cheat Sheet
7. Conditional (Ternary) Operator: Shortcuts for Decisions šÆ
The ternary operator is like a shortcut for a if-else
statement. It makes your code more concise by allowing you to write conditions in a single line.
Syntax:
condition ? valueIfTrue : valueIfFalse;
Example:
let age = 18; let canVote = (age >= 18) ? "Yes" : "No"; console.log(canVote); // Yes
Use the ternary operator when you need a quick, simple decision. It keeps your code clean and readable.
JavaScript operators Cheat Sheet
8. Unary Operators: One Operand, Big Impact šÆ
Unary operators only need one operand to perform their operation. The most common ones are:
typeof
: Returns the data type of a variable.++
/--
: Increment or decrement a value.!
: Negates a boolean value.
Example:
let x = 5; console.log(typeof x); // "number" console.log(typeof "Hello"); // "string"
JavaScript operators Cheat Sheet
9. Type Operators: Understanding Data Types š§āš»
Type operators help you determine the data type of a variable or check object relationships.
Examples:
typeof
: Tells you the data type of a variable.instanceof
: Checks whether an object is an instance of a specific class or constructor.
let name = "Alice"; console.log(typeof name); // "string" let date = new Date(); console.log(date instanceof Date); // true
JavaScript operators Cheat Sheet
10. Relational Operators: Finding Relationships š
Relational operators are used to test relationships between values, typically in object-related tasks.
in
: Checks if a property exists in an object.instanceof
: Checks if an object is an instance of a specific class or constructor.
let car = { make: "Toyota", model: "Corolla" }; console.log("make" in car); // true console.log(car instanceof Object); // true
JavaScript operators Cheat Sheet
11. Spread and Rest Operators: Flexibility with Arrays and Objects š
Introduced in ES6, the spread (...
) and rest (...
) operators provide great flexibility when working with arrays or objects.
- Spread (
...
): Expands an array or object into individual elements. - Rest (
...
): Collects arguments into an array.
Example:
let arr = [1, 2, 3]; let newArr = [...arr, 4, 5]; // [1, 2, 3, 4, 5] function sum(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0); } console.log(sum(1, 2, 3, 4)); // 10
JavaScript operators Cheat Sheet
12. Comma Operator: Evaluating Multiple Expressions š”
The comma operator allows you to evaluate multiple expressions in one line of code. Itās rarely used, but it can simplify your code in some cases.
Example:
let a = (1, 2, 3); console.log(a); // 3 (returns the last value)
While itās not commonly used, the comma operator can come in handy when you want to evaluate several expressions but only return the result of the last one.
JavaScript operators Cheat Sheet
Minor Operators: Other Useful Tools š§°
There are a few other operators that you might encounter occasionally:
delete
: Removes a property from an object.
let person = { name: "Areeb", age: 30 }; delete person.age; console.log(person); // { name: "Areeb" }
void
: Discards the return value of an expression.
void function() { console.log("This function runs, but its return value is discarded."); }();
new
: Creates an instance of an object.
function Car(make, model) { this.make = make; this.model = model; } let myCar = new Car("Toyota", "Corolla"); console.log(myCar); // Car { make: "Toyota", model: "Corolla" }
JavaScript operators Cheat Sheet
Conclusion
JavaScript operators are the glue that holds your code together. From basic arithmetic to advanced type-checking, mastering these 12 essential types will make you a more effective and efficient developer. Whether youāre adding numbers, comparing values, or working with arrays, operators are your go-to tools for getting the job done.
Also Read:
- JavaScript for Beginners: Master JavaScript in 30 Days
- How to Declare Variables in JavaScript: A Beginnerās Guide to var, let, and const
- Read Nore About JavaScript Operators at Programz.
FAQs
- What is the difference between
==
and===
in JavaScript?==
checks for loose equality, meaning it converts types if necessary.===
checks for strict equality, ensuring both value and type are the same.
- What is the use of the
typeof
operator?- The
typeof
operator returns the data type of a variable, such as"string"
,"number"
, or"object"
.
- The
- When should I use the spread operator?
- The spread operator (
...
) is great for expanding arrays or objects, especially when copying or merging them.
- The spread operator (
- What does the ternary operator do?
- The ternary operator is a shorthand for an
if-else
statement, allowing you to write conditional expressions in a single line.
- The ternary operator is a shorthand for an
- What are bitwise operators used for?
- Bitwise operators allow you to manipulate binary data at the bit level, making them useful for low-level programming tasks or performance optimization.