mrizwanashiq

Muhammad Rizwan Ashiq

Posted on May 30, 2023

Operators

What are Operators?

Operators are symbols that are used to perform operations on values (also known as operands). There are many types of operators in JavaScript, including arithmetic operators, assignment operators, comparison operators, logical operators, and more.

Here are some examples of common operators in JavaScript:

  1. Arithmetic operators: +, -, *, /, %, ++, --
  2. Assignment operators: =, +=, -=, *=, /=, %=
  3. Comparison operators: ==, !=, >, <, >=, <=
  4. Logical operators: &&, ||, !
  5. Ternary operator: ?
  6. Optional chaining operator: ?.
  7. Nullish coalescing operator: ??
  8. Typeof operator: typeof
  9. Delete operator: delete
  10. Comma operator: ,
  11. Spread operator: ...
  12. In operator: in
  13. Operator precedence

Arithmetic Operator

Perform arithmetic calculations on numbers, such as addition, subtraction, multiplication, division, and more. For example:

const x = 24;
const y = 10;

console.log(x + y); // 34 (Addition)
console.log(x - y); // 14 (Subtraction)
console.log(x * y); // 240 (Multiplication)
console.log(x / y); // 2.4 (Division)
console.log(x % y); // 4 (Modulo, returns the remainder of x / y)
Enter fullscreen mode Exit fullscreen mode

Assignment Operator

Mostly, you will use the assignment operator = to assign a value to a variable. For example:

const x = 10;
Enter fullscreen mode Exit fullscreen mode

It assigns the value 10 to the variable x. However, there are other assignment operators that you can use to assign a value to a variable. For example:

Note: 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.

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
Enter fullscreen mode Exit fullscreen mode

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

const x = 10;

x &&= 5; // Assigns 5 to x if x is true
x ||= 5; // Assigns 5 to x if x is false
x ??= 5; // Assigns 5 to x if x is null or undefined
Enter fullscreen mode Exit fullscreen mode

x &&= 5 is equivalent to x = x && 5, and same for x += 5, x -= 5, x *= 5, and 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
Enter fullscreen mode Exit fullscreen mode

Here, the logical AND assignment operator &&= is used to assign the value "Ali" to the name property of the object if the name property is true. Since the name property is true, 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
Enter fullscreen mode Exit fullscreen mode

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 false. Since the name property is true, the value "Rizwan" 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
Enter fullscreen mode Exit fullscreen mode

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 the name property is true, the value "Rizwan" is assigned to the name property.

Comparison Operator

Compares two values, (or more) and return a boolean result (true or false). For example:

console.log(10 > 5); // Output: true (10 is greater than 5)
console.log(10 < 5); // Output: false (10 is less than 5)
console.log(10 >= 5); // Output: true (10 is greater than or equal to 5)
console.log(10 <= 5); // Output: false (10 is less than or equal to 5)
console.log(10 == 5); // Output: false (equal)
console.log(10 != 5); // Output: true (not equal)
Enter fullscreen mode Exit fullscreen mode

There are two types of comparison operators:

  1. strict: ===, !==
  2. type-converting: ==, !=

For example:

console.log(10 == "10"); // Output: true
console.log(10 === "10"); // Output: false
Enter fullscreen mode Exit fullscreen mode

Strict Comparison Operator

The == operator is not strict, it converts the operands to the same type and then compares them. In the above example, the string "10" is converted to the number 10, and then compared.

Type-converting Comparison Operator

The === operator is strict, it does not convert the operands to the same type. In the above example, the string "10" is not converted to the number 10, and then compared.

So, it is recommended to use the === operator instead of the == operator. Similarly, it is recommended to use the !== operator instead of the != operator.

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
Enter fullscreen mode Exit fullscreen mode

In the above example, the == operator is used to compare two objects. But, it returns false because the objects are not the same. The == operator compares the objects by reference, not by value. So, it returns false if the objects are not the same. But, if the objects are the same, it returns true. Same meaning sharing same reference.

Logical Operator

Logical operators are symbols or keywords used to 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. For example:

const a = true;
const b = false;

console.log(a && b); // Output: false
Enter fullscreen mode Exit fullscreen mode

OR operator:

The || operator returns true if either operand is true, otherwise it returns false. For example:

const a = true;
const b = false;

console.log(a || b); // Output: true
Enter fullscreen mode Exit fullscreen mode

NOT operator:

The ! operator returns true if the operand is false, and false if the operand is true. For example:

const a = true;

console.log(!a); // Output: false
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Optional Chaining Operator (?.)

Working with nested objects can be a bit tricky. For example:

const person = {
    name: "Rizwan"
};

console.log(person.name); // Output: Rizwan
console.log(person.age); // Output: undefined
// This will error
console.log(person.address.city); // Output: Uncaught TypeError: Cannot read property 'city' of undefined
Enter fullscreen mode Exit fullscreen mode

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
// highlight-next-line
console.log(person.address && person.address.city); // Output: undefined
Enter fullscreen mode Exit fullscreen mode

But, this is not a good solution. The && operator is used to check if the left-hand side operand is true or false. If the left-hand side operand is true, it returns the right-hand side operand. If the left-hand side operand is false, it returns the left-hand side operand. So, it is not a good solution to use the && operator to avoid the error.

The optional chaining operator ?. is used 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?.city); // Output: undefined
Enter fullscreen mode Exit fullscreen mode

Here, the optional chaining operator ?. is used to avoid the error. If the address property is undefined, the optional chaining operator ?. returns undefined and does not throw an 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Here, x is 0, so the left-hand side operand x is returned.

typeof Operator

The typeof operator is a unary operator that returns a string indicating the type of variable or an expression. It has the following syntax:

typeof variable;
Enter fullscreen mode Exit fullscreen mode

or

typeof expression;
Enter fullscreen mode Exit fullscreen mode

The typeof operator returns one of the following strings:

  • undefined if the variable or expression is undefined
  • boolean if the variable or expression is a boolean value
  • string if the variable or expression is a string
  • number if the variable or expression is a number
  • object if the variable or expression is an object, array, or null
  • function if the variable or expression is a function

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'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

function add(x, y) {
    if (typeof x !== "number" || typeof y !== "number") {
        throw new Error("Invalid argument");
    }
    return x + y;
}
Enter fullscreen mode Exit fullscreen mode

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, an element from an array, or a variable. 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)
delete variable; // delete a variable (not recommended)
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Comma Operator

The comma operator , is used to evaluate multiple expressions, and returns the value of the last expression. For example:

const x = 10;
const y = 20;

const result = (x++, y++);
console.log(result); // Output: 20
Enter fullscreen mode Exit fullscreen mode

Here, the comma operator evaluates both expressions, and returns the value of the last expression y++. It is not recommended to use the comma operator. It is better to use separate statements instead of the comma operator. Just telling you for the sake of knowledge.

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
Enter fullscreen mode Exit fullscreen mode

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 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]
Enter fullscreen mode Exit fullscreen mode

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 }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

(1 + ( ( (2 *_ 3) _ 4 ) / 5) ) >> 6
// │ │ │ └─ 1. ─┘ │ │ │
// │ └─│─────── 2. ───│────┘ │
// └──────│───── 3. ─────│──────┘
//

 10 + 20 * 30
 │    └─ 1 ─┘
 └─ 2 ──────┘
Enter fullscreen mode Exit fullscreen mode

Here, the multiplication operator * has higher precedence than the addition operator +, so it is evaluated first. The result is then added to x. JavaScript has a precedence table that lists all operators in order of precedence.

Check this one

    1 + 8 * 4 / 5
    │    └─ 1 ─┘
    └─ 2 ──────┘
Enter fullscreen mode Exit fullscreen mode
   (1 + ( (2 ** 3) * 4 / 5) )
   │    │ └─ 1  ─┘        │ │
   │    └────── 2  ───────┘ │
   └────────── 3  ──────────┘
Enter fullscreen mode Exit fullscreen mode

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 ~x +x -x typeof x void 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
&& Logical AND x && y
`\ \ `
? : Conditional x ? y : z
= += -= *= /= %= **= <<= >>= >>>= &= ^= `\ =` Assignment
, 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 (? :)
  • Comma operator (,)
  • Operator precedence
  • typeof operator
  • delete operator
💖 💪 🙅 🚩
mrizwanashiq
Muhammad Rizwan Ashiq

Posted on May 30, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related