Home » JavaScript Operators

JavaScript Operators

JavaScript Operators

Introduction

In JavaScript, Operators is a special symbol used to perform operations on operands (values and variables).

Arithmetic Operators in JavaScript

Used for mathematical calculations

OperatorNameExample
+Additionx + y
Subtractionx – y
*Multiplicationx * y
/Divisionx/y
%Remainderx%y
++Increment (increments by 1)++x or x++
Decrement (decrements by 1)– -x or x- –
**Exponentiation (Power)x**y

Basic Arithmetic Operations in JavaScript


let a = 10;
let b = 5;

// Addition
let sum = a + b;
console.log(`Sum: ${sum}`);  // Output: Sum: 15

// Subtraction
let difference = a - b;
console.log(`Difference: ${difference}`);  // Output: Difference: 5

// Multiplication
let product = a * b;
console.log(`Product: ${product}`);  // Output: Product: 50

// Division
let quotient = a / b;
console.log(`Quotient: ${quotient}`);  // Output: Quotient: 2

// Modulus (Remainder)
let remainder = a % b;
console.log(`Remainder: ${remainder}`);  // Output: Remainder: 0

// Increment
a++;
console.log(`Increment: ${a}`);  // Output: Increment: 11

// Decrement
b--;
console.log(`Decrement: ${b}`);  // Output: Decrement: 4
JavaScript

These examples illustrate how arithmetic operators apply to variables or values for performing mathematical calculations, showcasing their fundamental role in programming logic and calculations within JavaScript.

Assignment Operators in JavaScript

OperatorNameExample
=Assignment operatora = 7; // 7
+=Addition assignmenta += 5; // a = a + 5
-=Subtraction Assignmenta -= 2; // a = a – 2
*=Multiplication Assignmenta *= 3; // a = a * 3
/=Division Assignmenta /= 2; // a = a / 2
%=Remainder Assignmenta %= 2; // a = a % 2
**=Exponentiation Assignmenta **= 2; // a = a**2

Basic Assignment Operators in JavaScript

let a = 10;
let b = 5;

// Addition Assignment
a += b;
console.log(`Addition Assignment: ${a}`);  // Output: Addition Assignment: 15

// Subtraction Assignment
a -= b;
console.log(`Subtraction Assignment: ${a}`);  // Output: Subtraction Assignment: 10

// Multiplication Assignment
a *= b;
console.log(`Multiplication Assignment: ${a}`);  // Output: Multiplication Assignment: 50

// Division Assignment
a /= b;
console.log(`Division Assignment: ${a}`);  // Output: Division Assignment: 10

// Modulus Assignment
a %= b;
console.log(`Modulus Assignment: ${a}`);  // Output: Modulus Assignment: 0

// Exponentiation Assignment
a **= b;
console.log(`Exponentiation Assignment: ${a}`);  // Output: Exponentiation Assignment: 100000

JavaScript

Comparison Operators in JavaScript

OperatorNameExample
==Equal to: returns true if the operands are equalx == y
!=Not equal to: returns true if the operands are not equalx != y
===Strict equal to: true if the operands are equal and of the same typex === y
!==Strict not equal to: true if the operands are equal but of different type or not equal at allx!==y
>Greater than: true if left operand is greater than the right operandx>y
>=Greater than or equal to: true if left operand is greater or equal to than the right operandx>=y
<Less than: true if left operand is less than the right operandx<y
<=Less than or equal to: true if left operand is less than greater or equal to the right operandx<=y

Equality (==) and Strict Equality (===)

  • Equality checks if the values are equal after type coercion.
let a = 5; // Number
let b = "5"; // String

console.log(a == b); // true, because '5' is coerced to a number
JavaScript
  • Strict Equality checks if the values are equal and of the same type, without type coercion.
let a = 5; // Number
let b = "5"; // String

console.log(a === b); // false, because one is a number and the other is a string
JavaScript

Not Equal (!=) and Strict Not Equal (!==)

  • Not Equal checks if the values are not equal after type coercion.
let a = 5;
let b = "10";

console.log(a != b); // true, because 5 is not equal to 10
JavaScript
  • Strict Not Equal checks if the values are not equal or not of the same type.
let a = 5;
let b = "5";

console.log(a !== b); // true, because one is a number and the other is a string
JavaScript

Greater Than (>) and Less Than (<)

  • Greater Than checks if the left operand is greater than the right operand.
let score = 85;

console.log(score > 75); // true, because 85 is greater than 75
JavaScript
  • Less Than checks if the left operand is less than the right operand.
let age = 18;

console.log(age < 21); // true, because 18 is less than 21
JavaScript

Greater Than or Equal to (>=) and Less Than or Equal to (<=)

  • Greater Than or Equal to checks if the left operand is greater than or equal to the right operand.
let temp = 32;

console.log(temp >= 32); // true, because 32 is equal to 32
JavaScript
  • Less Than or Equal to checks if the left operand is less than or equal to the right operand.
let items = 3;

console.log(items <= 5); // true, because 3 is less than 5
JavaScript

These examples explains how comparison operators can be used to evaluate and compare values in JavaScript.

Comparison and Difference Between == and === in Javascript

In JavaScript, == and === are comparison operators used to compare values. They both serve the purpose of making comparisons, but they behave differently due to their strictness. Let’s explain the differences between them in-depth, along with suitable examples.

1. == (Equality Operator):

  • The == operator is also known as the equality operator, and it checks if two values are equal in a loose or non-strict manner.
  • It does type coercion, meaning it will attempt to convert the operands to a common data type before making the comparison.
  • If the values on both sides of == are equal in terms of their values, it returns true.

Example of ==:

"5" == 5 // true (String "5" is coerced to a number)
1 == true // true (Boolean true is coerced to the number 1)
0 == false // true (Boolean false is coerced to the number 0)
JavaScript

In these examples, == compares values after performing type coercion. It considers different types to be equal under certain conditions.

2. === (Strict Equality Operator):

  • The === operator is known as the strict equality operator, and it checks if two values are equal in a strict manner.
  • It does not perform type coercion; it requires both the value and the data type to be the same.
  • If the values on both sides of === are identical in both value and data type, it returns true.

Example of ===:

"5" === 5 // false (String "5" and number 5 have different data types)
1 === true // false (Number 1 and Boolean true have different data types)
10 === 10 // true (Number 10 and Number 10 have same data types and values as well)
JavaScript

In these examples, === compares values without performing type coercion. It only considers values of the same data type to be equal.

When to Use Each Operator:

  • Use === (strict equality) when you want to ensure both the value and data type are the same. It’s a safer choice in most cases as it avoids unexpected type coercion.
  • Use == (equality) when you need to check for loose equality, especially if you expect type conversion to be helpful.
S.no=====
1Compares two operandsCompares two operands
2returns true if operands have the same data type and same value, returns false if the values differ.returns true only if operands are of same data type and same value, otherwise returns false.
3In case both operands are of different data types, it performs type conversion of one operand in order to make the data types of the operands the same.In case both operands are of different data type, it doesn’t perform type conversion of the operands.
4Also known as loose equalityAlso known as strict equality
5Follows abstract equality comparison algorithm.Follows strict equality comparison algorithm.
6Type coercion is done. Even if the values are of different types, the values are considered equal.No type coercion is done. If the values are of different types, the values are considered unequal.
7In JavaScript, null and undefined are considered equal when compared using ==.When using ===, null and undefined are not considered equal because they are of different types.

Logical Operators

OperatorNameExample
&&Logical AND: true if both the operands are true, else returns falsex && y
||Logical OR: true if either of the operands is true; returns false if both are falsex||y
!Logical NOT: true if the operand is false and vice-versa.!(x==y)

Logical AND (&&)

The && operator returns true if both operands are truthy, and false otherwise. It’s often used in conditional statements to ensure multiple conditions are met.

let a = 5;
let b = 10;

if (a > 0 && b > 0) {
    console.log('Both numbers are positive.');
} else {
    console.log('One or both numbers are not positive.');
}
// Output: Both numbers are positive.

JavaScript

Logical OR (||)

The || operator returns true if at least one of the operands is truthy. It’s useful for checking if any one of multiple conditions is met.

let hour = 20;

if (hour < 9 || hour > 17) {
    console.log('The office is closed.');
} else {
    console.log('The office is open.');
}
// Output: The office is closed.

JavaScript

Logical NOT (!)

The ! operator inverts the truthiness of an operand. It’s commonly used to negate a condition.

let isWeekend = false;

if (!isWeekend) {
    console.log('It is a weekday.');
} else {
    console.log('It is the weekend.');
}
// Output: It is a weekday.
JavaScript

Conclusion

JavaScript operators are indispensable tools in the arsenal of a web developer, enabling the manipulation and comparison of values, the creation of logical conditions, and the performance of mathematical calculations. By mastering both basic and advanced operators, developers can implement sophisticated functionality and logic into their web applications. Understanding the nuances of each operator, such as when to use strict equality over loose equality or how to effectively combine logical operators, is crucial for writing efficient, readable, and maintainable JavaScript code. Through practical application and exploration of these operators, developers can leverage the full power of JavaScript to create dynamic, responsive, and interactive user experiences.

Frequently Asked Questions

Q1. What is the purpose of using arithmetic operators in JavaScript?

Ans: Arithmetic operators allow you to perform mathematical calculations within your code. They are essential for tasks ranging from basic arithmetic to complex numerical computations, enabling dynamic content and interactive web applications.


Q2. How do assignment operators enhance code efficiency?

Ans: Assignment operators provide a shorthand for updating the value of variables. For instance, a += 5 is a concise way to add 5 to the current value of a. This makes the code more readable and reduces the amount of code needed for variable manipulation.


Q3. When should I use strict equality (===) over equality (==) in JavaScript?

Ans: Strict equality (===) should be used when you want to check both the value and the type of two variables, as it does not perform type coercion. This leads to more predictable and bug-free code, especially when dealing with different data types.


Q4. Can you explain the difference between the logical AND (&&) and logical OR (||) operators?

Ans: The logical AND (&&) operator returns true if both operands are truthy, whereas the logical OR (||) operator returns true if at least one operand is truthy. They are used to combine multiple conditions in control structures like if statements, allowing for complex decision-making.


Q5.Why is the logical NOT (!) operator useful?

Ans: The logical NOT (!) operator is useful for inverting boolean values. It can change true to false and vice versa. This is particularly handy in conditional logic for reversing a condition’s outcome or checking for the absence of a condition.