javascript operators

The Ultimate Guide to JavaScript Operators: 12 Essential Types You Need to Know

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.

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

Arithmetic 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

Assignment 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

Comparison 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): Returns true if both conditions are true.
  • || (OR): Returns true 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

Logical 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 of a and b 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 and b.

Scenario 2: console.log(a | b);

  • a is 5 (binary: 0101)
  • b is 3 (binary: 0011)
  • The | operator compares each bit of a and b 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 or b (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 of a and b and returns 1 if the bits are different.
  • The result is 6 (binary: 0110) because the bits that are different between a and b are set to 1 in the result.

Scenario 4: console.log(~a);

  • a is 5 (binary: 0101)
  • The ~ operator inverts all the bits of a.
  • 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

Bitwise 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

String 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

Conditional (Ternary) Operator: Shortcuts for Decisions šŸŽÆ

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

Unary 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

Type 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

Relational 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

Spread and Rest 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

Comma 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

Minor 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:

FAQs

  1. 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.
  2. What is the use of the typeof operator?
    • The typeof operator returns the data type of a variable, such as "string", "number", or "object".
  3. When should I use the spread operator?
    • The spread operator (...) is great for expanding arrays or objects, especially when copying or merging them.
  4. 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.
  5. 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.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *