Understanding JavaScript Operators

Operators play a crucial role in programming by enabling us to perform various operations on data. In JavaScript, operators are symbols or keywords that allow us to manipulate and combine values. They provide the foundation for performing arithmetic calculations, making comparisons, assigning values, and more. Let’s delve into the world of JavaScript operators and explore their significance.

Atul jha
18 min readJul 2, 2023
Understanding JavaScript Operators

What are operators?

Operators are symbols or keywords used to perform operations on values in JavaScript. They can be classified into different categories based on their functionality, such as Arithmetic operators, Assignment operators, Comparison operators, Logical operators, Bitwise operators, and more. Each category serves a specific purpose and allows us to work with data in different ways.

Operators in JavaScript are like tools in a toolbox. Just as a handyman uses different tools to fix or build things, programmers use operators to manipulate and work with data.

Importance of Operators:

Operators are essential for performing computations, making decisions, and manipulating data in programming. They enable us to perform mathematical calculations, concatenate strings, compare values, control program flow, and handle complex operations. By using operators effectively, we can write powerful and efficient code that solves a wide range of problems.

Understanding JavaScript operators is fundamental to becoming proficient in the language. By mastering these operators, you’ll have the ability to manipulate data, perform calculations, make decisions, and create powerful programs. So, let’s dive into the world of JavaScript operators and explore their vast potential.

Next, we will delve into each category of JavaScript operators in more detail, providing examples and explanations to enhance your understanding.

1. Arithmetic Operator:

Arithmetic operators in JavaScript allow us to perform mathematical calculations on numbers. They include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).

  1. Addition Operator (+): The addition operator is used to add two or more numbers or concatenate strings. For example:
  • 5 + 3 would evaluate to 8.
  • "Hello " + "World" would result in "Hello World".

2. Subtraction Operator (-): The subtraction operator subtracts one number from another. For example:

  • 10 - 5 would evaluate to 5.

3. Multiplication Operator (*): The multiplication operator multiplies two numbers. For example:

  • 4 * 2 would evaluate to 8.

4. Division Operator (/): The division operator divides one number by another. For example:

  • 10 / 2 would evaluate to 5.

5. Modulus Operator (%): The modulus operator returns the remainder of a division operation. For example:

  • 10 % 3 would evaluate to 1, as 10 divided by 3 leaves a remainder of 1.

1.1. Increment and Decrement Operators:

JavaScript also provides increment (++) and decrement ( ) operators to conveniently increase or decrease the value of a variable by 1.

  1. Increment Operator (++): The increment operator increases the value of a variable by 1. It can be used as a prefix (++x) or postfix (x++) operator. For example:
  • let x = 5;
  • x++; // x becomes 6

2. Decrement Operator ( ): The decrement operator decreases the value of a variable by 1. It can be used as a prefix ( — x) or postfix (x — ) operator. For example:

  • let y = 10;
  • y--; // y becomes 9

1.2. Operator Precedence and Associativity:

Operator precedence determines the order in which operators are evaluated in an expression. It helps to resolve any ambiguity in calculations.

  1. Operator Precedence: Operators in JavaScript follow a specific precedence, where certain operators are evaluated before others. For example, multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-). If there are multiple operators in an expression, JavaScript evaluates them based on their precedence rules. Parentheses can be used to override the default precedence and control the order of evaluation.
  2. Operator Associativity: Operator associativity defines the order in which operators with the same precedence are evaluated. JavaScript has left-to-right associativity for most operators, meaning that if there are multiple operators with the same precedence, they are evaluated from left to right.

Understanding operator precedence and associativity is important as it ensures that expressions are evaluated correctly and produce the desired results.

2. Assignment Operators:

Assignment operators are used to assign values to variables. They provide a convenient and concise way to update the value of a variable based on its current value or the result of an expression. There are two main types of assignment operators: the simple assignment operator and compound assignment operators.

2.1. Simple Assignment Operator (=):

The simple assignment operator (=) is the most basic form of assignment operator in JavaScript. It assigns the value on the right-hand side to the variable on the left-hand side. For example:

let x = 5;

In this case, the value 5 is assigned to the variable x. The simple assignment operator is used to initialize variables and update their values throughout the program.

2.2. Compound Assignment Operators:

Compound assignment operators combine the assignment operation with another operation, such as addition, subtraction, multiplication, division, or modulus. They provide a shorthand way to perform an operation and assign the result to the variable.

  • Addition Assignment (+=): The addition assignment operator (+=) adds the value on the right-hand side to the current value of the variable and assigns the result back to the variable. For example:
let x = 5;
x += 3; // equivalent to x = x + 3
console.log(x);

// After executing this code, the value of x will be 8.
  • Subtraction Assignment (-=): The subtraction assignment operator (-=) subtracts the value on the right-hand side from the current value of the variable and assigns the result back to the variable. For example:
let x = 10;
x -= 4; // equivalent to x = x - 4
console.log(x);

// After executing this code, the value of x will be 6.
  • Multiplication Assignment (*=): The multiplication assignment operator (*=) multiplies the value on the right-hand side with the current value of the variable and assigns the result back to the variable. For example:
let x = 2;
x *= 5; // equivalent to x = x * 5
console.log(x);

// After executing this code, the value of x will be 10.
  • Division Assignment (/=): The division assignment operator (/=) divides the current value of the variable by the value on the right-hand side and assigns the result back to the variable. For example:
let x = 12;
x /= 3; // equivalent to x = x / 3
console.log(x);

// After executing this code, the value of x will be 4.
  • Modulus Assignment (%=): The modulus assignment operator (%=) divides the current value of the variable by the value on the right-hand side and assigns the remainder back to the variable. For example:
let x = 15;
x %= 4; // equivalent to x = x % 4
console.log(x);

// After executing this code, the value of x will be 3.

Compound assignment operators are not only shorter but also make the code more readable and concise by combining the operation and assignment into a single statement. They are commonly used in loops, calculations, and other situations where updating variables is required.

3. Comparison Operators:

Comparison operators are used to compare values and determine the relationship between them. These operators return a boolean value (true or false) based on the comparison result. There are several types of comparison operators:’

3.1. Equal to (==) and Not equal to (!=):

The equal to (==) operator compares two values and returns true if they are equal, and false otherwise. The not equal to (!=) operator does the opposite and returns true if the values are not equal. For example:

let x = 5;
let y = 8;
console.log(x == y); // false
console.log(x != y); // true

3.2. Strict equality (===) and Strict inequality (!==):

The strict equality (===) operator compares both the value and the data type of the operands. It returns true if both values are equal and of the same type. The strict inequality (!==) operator does the opposite and returns true if the values are either not equal or not of the same type. For example:

let x = 5;
let y = '5';
console.log(x === y); // false
console.log(x !== y); // true

But lots of people has the confusion between “Equal to (==) and Not equal to (!=)” & “Strict equality (===) and Strict inequality (!==)”. So here is an tabular comparison using an example:

The main difference between the two sets of operators is in their comparison approach.

  • The Equal to (==) and Not equal to (!=) operators compare the values of the operands and perform type coercion if needed. They convert the operands to a common type and then compare their values.
  • On the other hand, the Strict equality (===) and Strict inequality (!==) operators perform a strict comparison. They compare both the values and the data types of the operands. If the values are of different types, the result is always false.

Note: In general, it is recommended to use the strict equality (===) and strict inequality (!==) operators in JavaScript to ensure precise comparisons and avoid unexpected type coercion.

3.3. Greater than (>) || Greater than or equal to (>=) || Less than (<) || Less than or equal to (<=):

The greater than (>), greater than or equal to (>=), less than (<), and less than or equal to (<=) operators are used to compare numerical or alphabetical values. They return true if the specified condition is met and false otherwise. For example:

let x = 5;
let y = 8;
console.log(x > y); // false
console.log(x >= y); // false
console.log(x < y); // true
console.log(x <= y); // true

3.4. Operator Precedence in Comparisons:

Operator precedence determines the order in which operators are evaluated in an expression. Comparison operators have a lower precedence than arithmetic operators, but higher precedence than logical operators. This means that comparison operations are performed before logical operations in an expression. However, it’s always a good practice to use parentheses to make the order of evaluation explicit and avoid confusion. For example:

let result = 10 + 5 > 6 * 2;   // result will be true
let result2 = (10 + 5) > (6 * 2); // result2 will also be true

Understanding comparison operators is crucial for making decisions and controlling the flow of your program. These operators allow you to compare values, check conditions, and execute different blocks of code based on the comparison result. By mastering comparison operators, you can create more dynamic and flexible JavaScript programs.

4. Logical Operators:

Logical operators are used to perform logical operations on boolean values or expressions. These operators allow you to combine and manipulate boolean values to make decisions and control the flow of your code. There are three main logical operators in JavaScript:

4.1. Logical AND (&&):

The logical AND operator (&&) returns true if both operands are true, and false otherwise. It evaluates the operands from left to right and stops evaluation as soon as a false operand is encountered. If the left operand is false, the right operand is not evaluated. For example:

let a = 5;
let b = 10;
let c = 15;
console.log(a < b && b < c); // true
console.log(a < b && b > c); // false

4.2. Logical OR (||):

The logical OR operator (||) returns true if at least one of the operands is true, and false if both operands are false. It also evaluates the operands from left to right and stops evaluation as soon as a true operand is encountered. If the left operand is true, the right operand is not evaluated. For example:

let a = 5;
let b = 10;
let c = 15;
console.log(a < b || b < c); // true
console.log(a > b || b > c); // false

4.3. Logical NOT (!):

The logical NOT operator (!) is a unary operator that negates the boolean value of its operand. It returns true if the operand is false, and false if the operand is true. It effectively flips the truthiness or falsiness of the operand. For example:

let a = 5;
let b = 10;
console.log(!(a < b)); // false
console.log(!(a > b)); // true

Lets see a new term “Short-Circuit Evaluation”.

4.4. What is Short-circuit evaluation?

Short-circuit evaluation is a behavior of logical operators in JavaScript where the second operand is not evaluated if the result can be determined by evaluating only the first operand. This behavior is based on the logical principles that “false && anything” is always false and “true || anything” is always true. It can be useful for improving performance and avoiding unnecessary evaluations. For example:

let a = 5;
let b = null;
let result = a && b; // Since a is truthy, b is not evaluated, and result is null

4.5. What is Truthy and Falsy Values?

Every value has an inherent truthiness or falsiness. Truthy values are considered true in a boolean context, while falsy values are considered false. The falsy values in JavaScript are false, 0, empty strings (‘’), NaN, null, and undefined. All other values are considered truthy. This concept is important when using logical operators and conditional statements.

For example:

let a = 5;
let b = '';
console.log(a && true); // true (both operands are truthy)
console.log(b || false); // false (b is falsy)

Understanding logical operators and their behavior is crucial for building complex conditions and controlling the flow of your JavaScript code. By mastering logical operators, you can make more robust and effective decisions in your programs.

5. Bitwise operators:

Bitwise operators are used to perform operations on individual bits of binary representations of numbers. These operators allow you to manipulate and control the binary data at a lower level. There are several bitwise operators available in JavaScript:

5.1. Bitwise AND (&):

The bitwise AND operator (&) performs a bitwise AND operation between the corresponding bits of two operands. It returns a new number where each bit is set to 1 only if the corresponding bits of both operands are 1. For example:

let a = 5;    // Binary: 0101
let b = 3; // Binary: 0011
let result = a & b; // Binary result: 0001 (Decimal: 1)

5.2. Bitwise OR (|):

The bitwise OR operator (|) performs a bitwise OR operation between the corresponding bits of two operands. It returns a new number where each bit is set to 1 if at least one of the corresponding bits of the operands is 1. For example:

let a = 5;    // Binary: 0101
let b = 3; // Binary: 0011
let result = a | b; // Binary result: 0111 (Decimal: 7)

5.3. Bitwise XOR (^):

The bitwise XOR operator (^) performs a bitwise XOR (exclusive OR) operation between the corresponding bits of two operands. It returns a new number where each bit is set to 1 if the corresponding bits of the operands are different. For example:

let a = 5;    // Binary: 0101
let b = 3; // Binary: 0011
let result = a ^ b; // Binary result: 0110 (Decimal: 6)

5.4. Bitwise Left Shift (<<):

The bitwise left shift operator (<<) shifts the bits of the left operand to the left by a specified number of positions. It effectively multiplies the left operand by 2 raised to the power of the right operand. For example:

let a = 5;    // Binary: 0101
let result = a << 2; // Binary result: 010100 (Decimal: 20)

5.5. Bitwise Right Shift (>>):

The bitwise right shift operator (>>) shifts the bits of the left operand to the right by a specified number of positions. It effectively divides the left operand by 2 raised to the power of the right operand. For example:

let a = 20;   // Binary: 010100
let result = a >> 2; // Binary result: 000101 (Decimal: 5)

5.6. Bitwise Zero-fill Right Shift (>>>):

The bitwise zero-fill right shift operator (>>>) is similar to the bitwise right shift operator (>>), but it fills the shifted positions with zeros instead of replicating the sign bit. This operator is useful when working with unsigned 32-bit integers. For example:

let a = -20;   // Binary: 11111111111111111111111111101100 (32-bit representation)
let result = a >>> 2; // Binary result: 00111111111111111111111111111011 (Decimal: 1073741821)

Understanding bitwise operators is essential when dealing with low-level operations, binary data, or optimizing certain algorithms. They allow you to manipulate individual bits and perform bitwise calculations efficiently.

6. Unary Operators:

Unary operators are operators that perform operations on a single operand. They can be applied to variables, constants, or expressions. JavaScript provides several unary operators that you can use in your code:

6.1. Unary Plus (+):

The unary plus operator (+) can be used to convert an operand into a number. If the operand is not already a number, JavaScript tries to convert it. For example:

let num = "5";
let result = +num; // result will be 5 (a number)

6.2. Unary Minus (-):

The unary minus operator (-) negates the value of its operand. It converts the operand into a number and then applies the negation. For example:

let num = 5;
let result = -num; // result will be -5

Understanding unary operators is important for performing various operations on variables and values in JavaScript. They provide flexibility and convenience in manipulating data and checking the type of values.

7. typeof Operator:

The typeof operator returns a string indicating the type of its operand. It is often used to check the type of a variable or value. For example:

let num = 5;
let str = "Hello";
let bool = true;

console.log(typeof num); // "number"
console.log(typeof str); // "string"
console.log(typeof bool); // "boolean"

8. delete Operator:

The delete operator is used to delete an object’s property or an element of an array. It can also be used to delete a variable declared with the var keyword (in non-strict mode). For example:

let obj = { name: "John", age: 25 };
delete obj.age; // deletes the 'age' property from the 'obj' object

let arr = [1, 2, 3];
delete arr[1]; // deletes the element at index 1 from the 'arr' array

9. Ternary (Conditional) Operator:

The ternary operator, also known as the conditional operator, is a compact way to write conditional expressions in JavaScript. It allows you to make decisions based on a condition and choose one of two expressions to evaluate.

9.1. The syntax of the ternary operator is as follows:

condition ? expression1 : expression2
  • The condition is a boolean expression that evaluates to either true or false.
  • If the condition is true, expression1 is executed and its value is returned.
  • If the condition is false, expression2 is executed and its value is returned.

9.2. Usage:

The ternary operator is commonly used when you want to assign a value or perform an action based on a condition. It provides a concise way to write conditional statements without the need for an if-else block.

Example 1:

let num = 10;
let result = (num > 5) ? "Greater than 5" : "Less than or equal to 5";
console.log(result); // Output: Greater than 5

In this example, the condition num > 5 is evaluated. If the condition is true (which it is because num is 10), the expression "Greater than 5" is assigned to the result variable. If the condition is false, the expression "Less than or equal to 5" is assigned.

9.3. Evaluation:

The ternary operator is evaluated from left to right. First, the condition is evaluated. If the condition is true, the expression1 is evaluated and returned. If the condition is false, the expression2 is evaluated and returned. Only one of the expressions is executed, depending on the condition’s truthiness.

The ternary operator is a powerful tool for writing concise and readable code when you have simple conditional statements. However, it’s important to use it judiciously to maintain code readability and avoid excessive complexity.

10. String Concatenation Operator:

The string concatenation operator (+) is used to combine or join strings together. It allows you to create a single string by combining two or more strings.

10.1. Concatenating strings with the + operator:

The most common use of the string concatenation operator is to join two or more strings. When the + operator is used with strings, it performs string concatenation.

Example 1:

let firstName = "Meenal";
let lastName = "Oza";
let fullName = firstName + " " + lastName;
console.log(fullName); // Output: Meenal Oza

In this example, we have three strings: firstName, a space (" "), and lastName. By using the + operator, we concatenate these strings to form the fullName.

10.2. Implicit and explicit type conversion in string concatenation:

JavaScript is a dynamically typed language, meaning variables can change their data type during runtime. When using the + operator for string concatenation, JavaScript performs type conversion if the operands are not strings.

Example 2:

let num = 42;
let str = "The answer is: " + num;
console.log(str); // Output: The answer is: 42

In this example, we have a numeric variable num, and we concatenate it with the string "The answer is: ". JavaScript automatically converts the numeric value to a string before concatenating it.

Example 3:

let x = "5";
let y = 10;
let result = x + y;
console.log(result); // Output: "510"

In this example, we have a string variable x containing the character "5" and a numeric variable y with the value 10. When we concatenate x and y, JavaScript implicitly converts y to a string and then performs string concatenation, resulting in "510".

Explicit conversion can also be done using the toString() method or by using String() function.

Example 4:

let num = 123;
let str = num.toString();
console.log(typeof str); // Output: string

In this example, we use the toString() method to explicitly convert the numeric variable num to a string.

String concatenation with the + operator is a fundamental operation in JavaScript, used extensively when working with strings and building dynamic content. However, it’s important to be mindful of type conversions, especially when dealing with mixed data types, to avoid unexpected results.

Operator Precedence and Associativity:

Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated first, followed by those with lower precedence. Operator associativity determines the order in which operators with the same precedence are evaluated.

Understanding the order of evaluation of operators:

Operator precedence is crucial for understanding how expressions are evaluated. It ensures that operators are applied in the correct order to produce the expected results.

For example, in the expression 3 + 4 * 2, the multiplication operator (*) has higher precedence than the addition operator (+). As a result, the multiplication is evaluated first, followed by the addition:

3 + 4 * 2
3 + (4 * 2)
3 + 8
11

Parentheses for changing precedence:

Parentheses can be used to override the default precedence and enforce a specific order of evaluation. Expressions within parentheses are evaluated first, regardless of the precedence of the operators involved.

For example, in the expression (3 + 4) * 2, the addition inside the parentheses is evaluated first, and then the result is multiplied by 2:

(3 + 4) * 2
7 * 2
14

Associativity of operators (left-to-right or right-to-left):

When operators have the same precedence, their associativity determines the order in which they are evaluated. Associativity can be left-to-right or right-to-left.

For example, the addition operator (+) has left-to-right associativity. So, in the expression 10 + 5 + 2, the addition is performed from left to right:

10 + 5 + 2
15 + 2
17

On the other hand, the assignment operator (=) has right-to-left associativity. This means that expressions like a = b = c are evaluated from right to left. First, b is assigned the value of c, and then a is assigned the value of b:

a = b = c
a = (b = c)
a = c

Understanding operator precedence and associativity is essential for writing correct and predictable JavaScript code. It helps ensure that expressions are evaluated in the desired order and can prevent unexpected results.

Example time:

We are going to build a basic calculator in which we are using Arithmetic operators to handle all the calculations. (Even if you have basic knowledge of HTML & CSS, that will be suffice). Firstly lets see the output & then breakdown how we used operators in it:

Here’s an code of how you can implement a basic calculator app using JavaScript:

<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<style>
#result {
font-size: 24px;
padding: 10px;
}
button {
width: 100px;
height: 25px;
font-size: 12px;
}
</style>
</head>
<body>
<h1>Calculator</h1>
<input type="number" id="num1" />
<select id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" id="num2" />
<button onclick="calculate()">Calculate</button>
<div id="result"></div>

<script>
function calculate() {
var num1 = parseFloat(document.getElementById("num1").value);
var num2 = parseFloat(document.getElementById("num2").value);
var operator = document.getElementById("operator").value;

var result;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
default:
result = "Invalid operator";
}

document.getElementById("result").innerText = "Result: " + result;
}
</script>
</body>
</html>

Explanation:

  1. Addition Operator (+): The addition operator is used in the calculate() function to add the num1 and num2 variables together when the operator value is +. It performs the arithmetic addition operation.
  2. Subtraction Operator (-): The subtraction operator is used in the calculate() function to subtract the num2 variable from num1 when the operator value is -. It performs the arithmetic subtraction operation.
  3. Multiplication Operator (*): The multiplication operator is used in the calculate() function to multiply the num1 and num2 variables when the operator value is *. It performs the arithmetic multiplication operation.
  4. Division Operator (/): The division operator is used in the calculate() function to divide the num1 by num2 when the operator value is /. It performs the arithmetic division operation.

These operators are essential for performing mathematical calculations in the calculator app. Based on the selected operator, the corresponding arithmetic operation is performed between the num1 and num2 values, and the result is displayed in the <div id="result"> element.

Additionally, the assignment operator (=) is used to assign the result of the calculation to the result variable, and the comparison operator (==) is used in the switch statement to match the selected operator value with the cases.

Conclusion:

Operators provide us with the ability to perform arithmetic, comparison, logical, and other operations in our programs. They play a crucial role in manipulating data and controlling the flow of our code.

Understanding and effectively using operators is essential for writing efficient and accurate JavaScript code. By grasping the concepts and syntax of different operators, we can perform calculations, make decisions, and create complex expressions.

--

--

Atul jha

I am a web enthusiast who is trying to pave his path towards being an awesome developer by exploring, learning & sharing the knowledge.