Operators in JavaScript

Operators in JavaScript

JavaScript is a powerful programming language for developing dynamic and interactive online applications, and operators are important in JavaScript. Operators are special symbols or keywords that execute value operations. In this article, we will look at the various types of JavaScript operators and learn how to apply them by looking at several code examples for each.

Types of JavaScript Operators

JavaScript operators are used to manipulate variables and values. They allow us to perform various tasks, such as arithmetic operations involving the assignment of values, the comparison of values, and more. Let's delve into the different types of operators.

1. Arithmetic operators

Arithmetic operators are a key feature of JavaScript that allows us to execute mathematical operations on numeric values. In JavaScript, arithmetic operators can be used in a variety of ways to perform computations or manipulate data.

JavaScript provides five primary arithmetic operators:

A. Addition Operator (+)

The addition operator, represented by the plus symbol (+), is used to add two or more values together.

Let’s take a look at a code example:

let sum = 5 + 3;
console.log(sum) // sum will be 8

In this example, the addition operator adds the values 5 and 3, resulting in the sum variable having a value of 8.

B. Subtraction Operator (-)

The subtraction operator, represented by the minus symbol (-), is used to subtract one value from another.

Let’s take a look at a code example:

let difference = 10 - 4;
console.log(difference) // difference will be 6

In this example, the subtraction operator subtracts 4 from 10, resulting in the difference variable having a value of 6.

C. Multiplication Operator (*)

The multiplication operator, represented by the asterisk symbol (*), is used to multiply two or more values.

Let’s take a look at a code example:

let product = 6 * 7;
console.log(product) // product will be 42

In this example, the multiplication operator multiplies 6 by 7, resulting in the product variable having a value of 42.

D. Division Operator (/)

The division operator, which is represented by the forward slash symbol (/), divides one value by another.

Let’s take a look at a code example:

let quotient = 20 / 4;
console.log(quotient) // quotient will be 5

In this example, the division operator divides 20 by 4, and the quotient variable has a value of 5.

E. Modulus Operator (%)

The modulus operator, represented by the percent symbol (%), returns the remainder when one value is divided by another.

Let’s take a look at a code example:

let remainder = 10 % 3;
console.log(remainder) // remainder will be 1

In this example, the modulus operator calculates the remainder when 10 is divided by 3, and the remainder variable has a value of 1.

2. Assignment operators

They allow you to assign values to variables, making it possible to store and manipulate data effectively. JavaScript assignment operators are fundamental tools for working with variables. They offer a way to update variable values without having to rewrite the variable name. JavaScript provides six primary assignment operators:

A. Assignment Operator (=)

The most basic assignment operator, represented by the equals sign (=), which is used to give a value to a variable.

Let’s take a look at a code example:

let x = 6; // x is assigned the value 6

In this example, the value 6 is assigned to the x variable. This is the most fundamental form of assignment operator.

B. Addition Assignment (+=)

This assignment operator (-=) allows you to add a value to a variable.

Let’s take a look at a code example:

let x = 10;
x+= 5;
console.log(x) // x becomes 15

In this example, the x variable is incremented by a value of 5, and this gives it a value of 15.

C. Subtraction Assignment (-=)

The subtraction assignment operator (-=) allows you to subtract a value from an existing variable.

Let’s take a look at a code example:

let balance = 100;
balance -= 25;
console.log(balance) // balance is now 75

In this example, the balance variable is reduced by 25 using the -= operator, leaving it with a value of 75.

D. Multiplication Assignment (*=)

The multiplication assignment operator (*=) multiplies a variable by a specified value.

Let’s take a look at a code example:

let quantity = 4;
quantity *= 5;
console.log(quantity) // quantity is now 20

In this example, the quantity variable is multiplied by 5 using the *= operator, resulting in it having a value of 20.

E. Division Assignment (/=)

The division assignment operator (/=) divides a variable by a given value and updates the variable’s value.

Let’s take a look at a code example:

let totalMarks = 100;
totalMarks /= 4;
console.log(totalMarks) // totalMarks is now 25

In this example, the totalMarks variable is divided by 4, and the result, 25, is stored back in totalMarks.

F. Modulus Assignment (%=)

When one value is divided by another, the modulus assignment operator (%=) calculates the remainder and assigns that remainder to a variable.

Let’s take a look at a code example:

let remainder = 17;
remainder %= 5;
console.log( // remainder is now 2

Here, the remainder variable stores the result of dividing 17 by 5, which leaves a remainder of 2.

3. Comparison operators

Comparison operators in JavaScript are fundamental tools for making decisions, comparing values, and controlling the flow of your code. They allow you to determine the relationships between variables, objects, and expressions. JavaScript provides three primary comparison operators:

A. Equality Operators (== and ===)

Javascript offers two types of equality operators:

  • The loose equality operator (==) checks if two values are equal, performing type coercion if needed.

Let’s take a look at a code example:

console.log(5 == "5"); // true

In this example, the loose equality operator compares the number 5 to the string "5," and they are considered equal because JavaScript performs type coercion to make the comparison.

  • The strict equality operator (===) checks if two values are equal without performing type coercion. They must have the same value and the same data type to be considered equal.

Let’s take a look at a code example:

console.log(5 === "5"); // false

In this example, the strict equality operator compares the number 5 to the string "5" and finds them not equal because they have different data types.

B. Inequality Operators (!= and !==)

The inequality operators are the counterparts of the equality operators:

  • The loose inequality operator (!=) checks if two values are not equal, performing type coercion if needed.

Let’s take a look at a code example:

console.log(5 != "10"); // true

In this example, the loose inequality operator compares the number 5 to the string "10," and they are considered not equal because JavaScript performs type coercion to make the comparison.

  • The strict inequality operator (!==) checks if two values are not equal without performing type coercion. They must have different values or different data types to be considered not equal.

Let’s take a look at a code example:

console.log(5 !== "5"); // true

In this example, the strict inequality operator compares the number 5 to the string "5" and finds them not equal because they have different data types.

C. Relational Operators (<, >, <=, >=)

Relational operators compare two values to determine their relationship in terms of magnitude:

  • The less than operator (<) checks if the value on the left is less than the value on the right.

Let’s take a look at a code example:

console.log(5 < 10); // true

In this example, the less than (<) operator checks if 5 is less than 10 and returns true.

  • The greater than operator (>) checks if the value on the left is greater than the value on the right.

Let’s take a look at a code example:

console.log(10 > 5); // true

In this example, the greater than operator (>) checks if 10 is greater than 5 and returns true.

  • The less than or equal to operator (<=) checks if the value on the left is less than or equal to the value on the right.

Let’s take a look at a code example:

console.log(5 <= 10); // true

In this example, the less than or equal to (<=) operator checks if 5 is less than or equal to 10 and returns true.

  • The greater than or equal to operator (>=) checks if the value on the left is greater than or equal to the value on the right.

Let’s take a look at a code example:

console.log(10 >= 5); // true

In this case, the greater than or equal to (>=) operator checks if 10 is greater than or equal to 5 and returns true.

4. Logical operators

Logical operators in JavaScript are powerful tools that enable you to make decisions, control program flow, and handle conditions efficiently. They allow you to control program flow, make informed decisions, and handle various conditions efficiently.

JavaScript provides three primary logical operators:

A. Logical AND (&&)

The logical AND operator (&&) returns true if and only if both of its operands are true. If any of the operands is false, the result will be false.

Let’s take a look at a code example:

let isSunny = true;
let isWarm = true;

if (isSunny && isWarm) {
  console.log("It's a beautiful day!");
} else {
  console.log("The weather is bad”)
}

In this example, we check whether it's sunny (isSunny) and warm (isWarm), and this will determine what to log out onto the screen.

B. Logical OR (||)

The logical OR operator (||) returns true if at least one of its operands is true. If both operands are false, the result will be false.

Let’s take a look at a code example:

let hasCoffee = true;
let hasTea = false;

if (hasCoffee || hasTea) {
  console.log("I can enjoy a hot beverage.");
} else {
  console.log("No hot drinks available.");
}

In this example, we check whether there's coffee (hasCoffee) or tea (hasTea) available. If either is true, the statement, "I can enjoy a hot beverage.", is logged out onto the screen.

C. Logical NOT (!)

The logical NOT operator (!) negates the value of its operand. If the operand is true, it becomes false, and vice versa.

Let’s take a look at a code example:

let isComing = true;

if (!isComing) {
  console.log("Dad is not coming; I can go out now.");
} else {
  console.log("I'll stay indoors; dad is coming.");
}

Here, the ! operator inverts the value of isComing, allowing you to determine whether dad is coming or not.

Combining Logical Operators

To generate more complex conditions, logical operators can be combined. You can use parentheses to control the order of operations, similar to mathematical expressions.

Let’s take a look at a code example:

let isDaytime = true;
let isCloudy = true;
let isCool = true;

if (isDaytime && (isCloudy || isCool)) {
  console.log("It's a nice day!");
} else {
  console.log("The conditions are not ideal.");
}

In this example, we check if it's daytime (isDaytime) and either cloudy (isCloudy) or cool (isCool) to determine whether it's a nice day.

5. Unary operators

Unary operators in JavaScript are essential tools for performing operations on a single operand, whether it's a variable or a value. They are essential for controlling program flow, performing type conversions, and handling various data-related tasks. JavaScript provides seven primary unary operators:

  1. Increment (++)

The increment operator (++) is used to increase a variable's value by one. It can be used as both a prefix (++x) and a postfix (x++) operator.

Let’s take a look at a code example:

let x = 5;
x++;
console.log(x) // x is now 6

In this example, the x variable is incremented by 1 using the postfix increment operator, resulting in x becoming 6.

B. Decrement (--)

The decrement operator (--), like the increment operator, is used to decrease the value of a variable by one. It can be used as either a prefix or a postfix operator.

Let’s take a look at a code example:

let y = 8;
--y;
console.log(y) // y is now 7

In this example, the prefix decrement operator is applied to y, decreasing its value to 7.

C. Unary Plus (+)

The unary addition operator (+) is used to change its operand to a number. It is often used to explicitly cast a value to a numeric data type.

Let’s take a look at a code example:

let numStr = "42";
let num = +numStr;
console.log(num) // num is now 42 (a number)

Here, the + operator is used to convert the string "42" into a numeric value, stored in the num variable.

D. Unary Minus (-)

The unary minus operator (-) negates and converts its operand to a number. It is used to make a number negative or to reverse the sign of a number.

Let’s take a look at a code example:

let positiveNum = 5;
let negativeNum = -positiveNum;
console.log(negativeNum) // negativeNum is -5

In this example, the negativeNum variable stores the negated value of positiveNum, making it -5.

E. Logical NOT (!)

The logical NOT operator (!) negates a Boolean value. It turns true to false and false to true.

Let’s take a look at a code example:

let isSunny = true;
let isRainy = !isSunny;
console.log(isRainy) // isRainy is false

In this example, the ! operator negates the value of isSunny, resulting in the value of isRainy being false.

F. Typeof Operator (typeof)

The typeof operator determines the data type of a value or variable. It returns a string that represents the data type.

Let’s take a look at a code example:

let alias = "Alice";
let type = typeof alias;
console.log(type) // type is "string"

In this example, the typeof operator is used to find the data type of the alias variable, which is a string.

G. Bitwise NOT (~)

The bitwise NOT operator (~) inverts an operand's bits, resulting in a binary NOT operation. It is rarely encountered in JavaScript programming.

Let’s take a look at a code example:

let num = 5;
let invertedNum = ~num;
console.log(invertedNum) // invertedNum is -6

In this code, the ~ operator inverts the bits of num, resulting in invertedNum being -6.

6. Ternary operator

The ternary operator, often referred to as the conditional operator, is a concise and powerful construct in JavaScript. It is a shorthand alternative to traditional if-else statements. It allows for conditional expressions in a single line of code, making it a valuable tool for simplifying decision-making processes.

The ternary operator is a JavaScript feature that takes three operands, which consist of a condition followed by two expressions.

The Ternary Syntax

The ternary operator's basic syntax is as follows:

condition ? expression1 : expression2

Condition: The condition that needs to be checked. If the condition is satisfied, expression1 is executed. If the condition is not met, expression2 is executed.

Ternary Operator vs. If-Else Statements

The ternary operator is often compared to if-else statements. While both can be used to achieve the same results, there are differences in terms of conciseness.

Here's a comparison between the two for a simple conditional statement:

A. Using if-else:

let isSunny = true;
let activity;

if (isSunny) {
  activity = "Go to the beach";
  console.log(activity)
} else {
  activity = "Stay indoors";
  console.log(activity)
}

B. Using the Ternary Operator:

let isSunny = true;
let activity = isSunny ? "Go to the beach" : "Stay indoors";
console.log(activity)

As you can see, the ternary operator reduces the code, making it more concise and easier to understand, especially for straightforward conditions.

7. Bitwise operator

Bitwise operators in JavaScript are powerful tools for performing operations at the binary level. They enable you to manipulate individual bits of data and perform various low-level operations. JavaScript provides seven primary bitwise operators:

A. Bitwise AND (&)

The bitwise AND operator (&) operates on each pair of corresponding bits in two operands. It returns 1 for bits that are 1 in both operands, and 0 otherwise.

Let’s take a look at a code example:

let result = 5 & 3;
console.log(result) // result is 1

In this example, the & operator performs a bitwise AND operation on 5, which has a binary value of 101 and 3, which has a binary value of 011, resulting in a binary value of 001, which is 1 in decimal.

B. Bitwise OR (|)

A bitwise OR operation is carried out by the bitwise OR operator (|) on each pair of corresponding bits in two operands. It returns 1 for bits that are 1 in either operand.

Let’s take a look at a code example:

let result = 5 | 3;
console.log(result) // result is 7

In this example, the | operator performs a bitwise OR operation on 5, which has a binary value of 101 and 3, which has a binary value of 011, resulting in a binary value of 111, which is 7 in decimal.

C. Bitwise XOR (^)

The bitwise XOR (exclusive OR) operator (^) performs a bitwise XOR operation on each set of corresponding bits in two operands. It returns 1 for bits that are different in the two operands.

Let’s take a look at a code example:

let result = 5 ^ 3;
console.log(result) // result is 6

In this example, the ^ operator performs a bitwise XOR operation on 5, which has a binary value of 101 and 3, which has a binary value of 011, resulting in a binary value of 110, which is 6 in decimal.

D. Bitwise NOT (~)

The bitwise NOT operator (~) changes the bits of its operand. It turns 1s into 0s and 0s into 1s.

Let’s take a look at a code example:

let result = ~5;
console.log(result) // result is -6

In this example, the ~ operator inverts the bits of 5, which is written as 00000101 in two’s complement form, resulting in 11111010, which is equivalent to -6 in two's complement form.

E. Left Shift (<<)

The left shift operator () shifts the first operand's bits to the left by the number of positions specified by the second operand. It effectively multiplies the first operand by 2 to the power of the second operand.

Let’s take a look at a code example:

let result = 5 << 2;
console.log(result) // result is 20

In this code, the << operator shifts the bits of 5, which is 101 in binary, two positions to the left, resulting in the binary 10100, which is 20 in decimal.

F. Right Shift (>>)

The right shift operator (>>) shifts the first operand's bits to the right by the number of positions specified by the second operand. It effectively divides the first operand by 2 to the power of the second operand.

Let’s take a look at a code example:

let result = 16 >> 2;
console.log(result) // result is 4

Here, the >> operator shifts the bits of 16, which has a binary value of 10000, two positions to the right, resulting in a binary value of 100, which is 4 in decimal.

G. Zero-fill Right Shift (>>>)

The zero-fill right shift operator (>>>) is identical to the right shift operator, but it uses zeros to fill the leftmost bits.

Let’s take a look at a code example:

let result = -16 >>> 2;
console.log(result) // result is 1073741820

In this code, the >>> operator shifts the bits of -16, which has a binary value of 11111111111111111111111111110000, two positions to the right, filling the leftmost bits with zeros. The result is 00111111111111111111111111111100, which is 1073741820 in decimal.

8. Type operators

Type operators in JavaScript are essential tools for determining the data type of values and variables. They help you ensure that the data you're working with is of the correct type and handle it appropriately.

JavaScript offers two primary type operators:

A. Typeof Operator (typeof)

The typeof operator is used to determine the data type of a value or expression. It returns a string that represents the operand's type.

Let’s take a look at a code example:

let alias = "Alice";
let age = 30;
let isMarried = false;

console.log(typeof alias); // "string"
console.log(typeof age); // "number"
console.log(typeof isMarried); // "boolean"

In this example, typeof is used to determine the data type of the name, age, and isMarried variables, providing string representations of their types.

B. Instanceof Operator (instanceof)

The instanceof operator determines if an object is an instance of a particular constructor or class. It evaluates to true if the object's prototype chain contains the specified constructor.

Let’s take a look at a code example:

class Animal {}
class Dog extends Animal {}

const fido = new Dog();

console.log(fido instanceof Dog); // true
console.log(fido instanceof Animal); // true

In this code, the instanceof operator checks if the fido object is an instance of the Dog class and the Animal class, returning true for both.

Conclusion

JavaScript operators are essential for performing various operations in your code, from basic arithmetic to complex conditional logic. Understanding and using these operators effectively will greatly enhance your ability to create dynamic and interactive web applications. You can explore each of these JavaScript operators further to gain a deeper understanding of their concepts.