Operators in JavaScript – Arithmetic, Comparison and Logical
Quick Answer: JavaScript operators perform calculations and compare values. They also help us make decisions using conditions. Arithmetic operators calculate amounts, comparison operators check values, and logical operators combine conditions.
We will learn these operators using a grocery shop checkout example. You will also see how JavaScript evaluates each expression.
1. Why Do We Need Operators in JavaScript?
Imagine you manage a grocery shop in Bengaluru. Every day, 1,000 customers buy different products. How will you calculate bills and check discounts?
You need to calculate totals, compare amounts, and check payment rules. JavaScript operators help us perform these tasks.
The Problem Without Operators
Consider three grocery items purchased by Priya. Their prices are sample values.
Example 1: A grocery bill without calculations
Purpose: Display product prices without calculating the total.
const ricePrice = 60;
const milkPrice = 30;
const breadPrice = 40;
console.log("Rice:", ricePrice);
console.log("Milk:", milkPrice);
console.log("Bread:", breadPrice);
Expected output
Rice: 60 Milk: 30 Bread: 40
This code displays prices, but it does not calculate the bill.
What Goes Wrong?
- The shopkeeper must calculate totals manually.
- Discount checks become difficult to manage.
- Payment conditions need repeated manual checks.
- Changes become harder when more products are added.
Now think about 1,000 customers and hundreds of products. Manual calculations are not practical.
The Solution With JavaScript Operators
JavaScript can calculate totals and check conditions automatically.
Example 2: Calculate a grocery bill
Purpose: Calculate the total, discount, and final amount.
const ricePrice = 60;
const milkPrice = 30;
const breadPrice = 40;
const total = ricePrice + milkPrice + breadPrice;
const discount = total * 0.10;
const finalAmount = total - discount;
console.log("Total:", total);
console.log("Discount:", discount);
console.log("Final amount:", finalAmount);
Expected output
Total: 130 Discount: 13 Final amount: 117
| Without operators | With operators |
|---|---|
| Calculate the total manually. | Use the addition operator. |
| Find discounts manually. | Use multiplication. |
| Subtract discounts manually. | Use subtraction. |
| Check payment rules manually. | Use comparison and logical operators. |
The Idea to Remember
- Operator = a symbol that performs an operation.
- Operand = a value used by an operator.
- Expression = values and operators combined together.
- Condition = an expression that produces a true or false result.
2. Types of Operators in JavaScript
JavaScript provides different operators for different tasks.
This article focuses on three important groups. They are arithmetic, comparison, and logical operators.
3. Arithmetic Operators in JavaScript
Arithmetic operators perform mathematical calculations. We use them to calculate grocery bills, discounts, and quantities.
Arithmetic Operators List
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
Addition | 60 + 30 | 90 |
- |
Subtraction | 60 - 30 | 30 |
* |
Multiplication | 60 * 3 | 180 |
/ |
Division | 60 / 3 | 20 |
% |
Remainder | 65 % 10 | 5 |
** |
Exponentiation | 2 ** 3 | 8 |
++ |
Increment by one | quantity++ | Increases quantity |
-- |
Decrement by one | quantity-- | Decreases quantity |
3.1 Addition Operator (+)
The addition operator adds two or more values.
Example 3: Add grocery product prices
const rice = 60;
const milk = 30;
const bread = 40;
const total = rice + milk + bread;
console.log(total);
Expected output
130
Important: The + operator also joins strings. For example, "Grocery " + "Bill" produces "Grocery Bill".
3.2 Subtraction Operator (-)
Subtraction finds the difference between two values. We can use it to remove a discount from the bill.
Example 4: Subtract a discount
const total = 130;
const discount = 13;
const finalAmount = total - discount;
console.log(finalAmount);
Expected output
117
3.3 Multiplication Operator (*)
Multiplication helps calculate the price of multiple items.
Example 5: Calculate the price of rice
const ricePrice = 60;
const quantity = 3;
const total = ricePrice * quantity;
console.log(total);
Expected output
180
3.4 Division Operator (/)
Division splits an amount into equal parts.
Example 6: Split a grocery bill
const total = 180;
const people = 3;
const share = total / people;
console.log(share);
Expected output
60
Important: JavaScript division can return decimal values. Division by zero does not throw a normal arithmetic error. It returns Infinity for a positive non-zero number divided by zero.
3.5 Modulus Operator (%)
The modulus operator returns the remainder after division.
Example 7: Find the remaining items
const totalItems = 17;
const itemsPerBag = 5;
const remainingItems = totalItems % itemsPerBag;
console.log(remainingItems);
Expected output
2
Five items fit into each full bag. Two items remain.
3.6 Exponentiation Operator (**)
Exponentiation raises a number to a power.
Example 8: Calculate a squared value
const numberOfBoxes = 4;
const result = numberOfBoxes ** 2;
console.log(result);
Expected output
16
3.7 Increment and Decrement Operators
Increment adds one to a variable. Decrement removes one.
Example 9: Update the item quantity
let quantity = 3;
quantity++;
console.log(quantity);
quantity--;
console.log(quantity);
Expected output
4 3
JavaScript supports prefix and postfix forms.
Example 10: Prefix and postfix increment
let quantity = 3;
console.log(quantity++);
console.log(quantity);
console.log(++quantity);
console.log(quantity);
Expected output
3 4 5 5
quantity++returns the old value first.++quantityincreases the value first.
4. Arithmetic Animation: How a Grocery Bill Is Calculated
This animation follows one grocery bill from product prices to the final amount. Each stage highlights the calculation in order.
Grocery bill calculation flow
Sample prices: rice ₹60, milk ₹30, bread ₹40
The animation highlights addition, discount calculation, subtraction, and the final bill.
5. Comparison Operators in JavaScript
Comparison operators compare two values. They return either true or false.
For example, a grocery shop may offer a discount above ₹500. We can compare the bill amount against that limit.
Comparison Operators List
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
Equal value after conversion | 5 == "5" | true |
=== |
Equal value and type | 5 === "5" | false |
!= |
Not equal after conversion | 5 != "6" | true |
!== |
Not equal value or type | 5 !== "5" | true |
> |
Greater than | 600 > 500 | true |
< |
Less than | 300 < 500 | true |
>= |
Greater than or equal | 500 >= 500 | true |
<= |
Less than or equal | 400 <= 500 | true |
5.1 Equal To (==) and Strict Equal To (===)
Both operators check whether values are equal. However, they handle data types differently.
Loose equality may convert values before comparing them. Strict equality does not perform that conversion.
Example 11: Compare a product quantity
console.log(5 == "5");
console.log(5 === "5");
console.log(10 === 10);
console.log(10 === "10");
Expected output
true false true false
Best practice: Prefer === for most comparisons. It avoids unexpected type conversion.
5.2 Not Equal (!=) and Strict Not Equal (!==)
These operators check whether two values are different.
Example 12: Check different values
console.log(5 != "5");
console.log(5 !== "5");
console.log(5 !== 8);
Expected output
false true true
5.3 Greater Than and Less Than
These operators compare numerical values.
Example 13: Check a discount threshold
const total = 650;
console.log(total > 500);
console.log(total < 1000);
console.log(total >= 650);
console.log(total <= 600);
Expected output
true true true false
6. Comparison Animation: Checking a Discount Rule
This diagram shows how the shop checks a customer's bill. The decision changes based on the comparison result.
Discount eligibility decision
The shop offers a sample discount for bills above ₹500.
The comparison result decides whether the customer receives the discount.
7. Logical Operators in JavaScript
Logical operators combine or reverse conditions. They help us build business rules.
For example, a customer may receive a discount only when two rules are satisfied. The bill must reach ₹500, and the customer must have a membership.
Logical Operators List
| Operator | Meaning | Example | Result |
|---|---|---|---|
&& |
AND | true && true | true |
|| |
OR | true || false | true |
! |
NOT | !true | false |
7.1 Logical AND (&&)
AND returns true only when both conditions are true.
Example 14: Check membership and bill amount
const total = 650;
const isMember = true;
const eligible = total >= 500 && isMember;
console.log(eligible);
Expected output
true
Both conditions are true, so the customer qualifies.
7.2 Logical OR (||)
OR returns true when at least one condition is true.
Example 15: Check two discount options
const hasMembership = false;
const hasCoupon = true;
const eligible = hasMembership || hasCoupon;
console.log(eligible);
Expected output
true
The customer has a coupon, so the result is true.
7.3 Logical NOT (!)
NOT reverses a boolean value. True becomes false, and false becomes true.
Example 16: Check whether a customer is not a member
const isMember = false;
console.log(!isMember);
Expected output
true
8. Logical Animation: How Multiple Conditions Work
This animation shows two eligibility checks entering a logical AND operation. The result controls the discount decision.
Membership discount rule
Both conditions must be true for this sample offer.
The AND operation returns true because both grocery shop conditions pass.
Truth Tables
A truth table shows every possible result for logical conditions.
| A | B | A && B |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
| A | B | A || B |
|---|---|---|
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
| A | !A |
|---|---|
| true | false |
| false | true |
9. Combining Arithmetic, Comparison and Logical Operators
Real applications often use multiple operator types together. Let's calculate a grocery bill and check discount eligibility.
Example 17: Complete grocery discount calculation
Purpose: Calculate the final amount for a qualifying customer.
const ricePrice = 200;
const milkPrice = 100;
const breadPrice = 250;
const isMember = true;
const total = ricePrice + milkPrice + breadPrice;
const isEligible = total >= 500 && isMember;
let discount = 0;
if (isEligible) {
discount = total * 0.10;
}
const finalAmount = total - discount;
console.log("Total:", total);
console.log("Eligible:", isEligible);
console.log("Discount:", discount);
console.log("Final amount:", finalAmount);
Expected output
Total: 550 Eligible: true Discount: 55 Final amount: 495
Step-by-Step Code Breakdown
- We add the three product prices using
+. - We compare the total with ₹500 using
>=. - We combine the bill and membership checks using
&&. - We calculate the discount using
*. - We subtract the discount using
-.
10. Operator Precedence and Parentheses
Operator precedence decides which operation runs first. Parentheses can change that order.
Example 18: Understand calculation order
console.log(10 + 5 * 2);
console.log((10 + 5) * 2);
Expected output
20 30
Multiplication runs before addition in the first expression. Parentheses make addition run first in the second expression.
Best practice: Use parentheses when an expression may be hard to read. Clear code is easier to review and maintain.
11. Short-Circuit Evaluation
JavaScript logical operators can stop evaluating early. This behavior is called short-circuit evaluation.
AND Short-Circuit
AND stops when it finds a false value. The final result cannot become true after that point.
Example 19: AND stops after false
function checkCoupon() {
console.log("Coupon checked");
return true;
}
const isMember = false;
const eligible = isMember && checkCoupon();
console.log(eligible);
Expected output
false
The function does not run. The first condition is already false.
OR Short-Circuit
OR stops when it finds a true value. The final result is already known.
Example 20: OR stops after true
function checkCoupon() {
console.log("Coupon checked");
return true;
}
const hasMembership = true;
const eligible = hasMembership || checkCoupon();
console.log(eligible);
Expected output
true
The function does not run because the first condition is true.
12. Common Mistakes and Best Practices
Mistake 1: Using == Instead of ===
Loose equality can convert values before comparison.
Avoid this
console.log(10 == "10");
Prefer this
console.log(10 === 10);
Mistake 2: Confusing + With Numeric Addition
The plus operator joins strings when string values are involved.
Example 21: String concatenation
console.log(10 + "20");
Expected output
1020
Convert input to a number when you need arithmetic.
Correct approach
const quantity = Number("20");
console.log(10 + quantity);
Expected output
30
Mistake 3: Ignoring Operator Precedence
Long expressions can be difficult to understand. Use parentheses to show your intention.
Mistake 4: Using Increment on a Constant
A variable declared with const cannot be reassigned.
Incorrect example
const quantity = 3;
quantity++;
This causes a TypeError because the constant cannot be reassigned.
Correct example
let quantity = 3;
quantity++;
console.log(quantity);
Expected output
4
Mistake 5: Assuming Logical Operators Always Return Booleans
JavaScript && and || return operand values. They do not always return true or false.
Example 22: Logical operators return values
console.log("Rice" || "Milk");
console.log(0 || 100);
console.log("Rice" && "Milk");
Expected output
Rice 100 Milk
|| returns the first truthy operand. && returns the first falsy operand, or the last operand when all are truthy.13. How This Topic Comes Up in Interviews
Question 1: What is the difference between == and ===?
What the interviewer expects: Explain type conversion and strict comparison.
Strong answer: "Both operators compare values. The double equal operator may convert types before comparing. The triple equal operator checks both value and type. I prefer triple equal for predictable comparisons."
Question 2: What is the difference between && and ||?
Strong answer: "AND needs both conditions to be truthy. OR needs at least one truthy condition. Both operators use short-circuit evaluation. They return operand values, not always boolean values."
Question 3: What does the modulus operator do?
Strong answer: "The modulus operator returns the remainder after division. For example, 17 modulo 5 returns 2. I can use it to find leftover grocery items after packing equal groups."
Question 4: What is short-circuit evaluation?
Strong answer: "JavaScript may stop checking a logical expression early. AND stops when it finds a falsy value. OR stops when it finds a truthy value. This can avoid unnecessary function calls."
Junior, Senior and Architect Expectations
- Junior: Know the operators and explain their results.
- Senior: Explain coercion, precedence, short-circuiting, and edge cases.
- Architect: Explain how clear conditions reduce defects in business rules.
14. Hands-On Practice
Beginner Exercise: Grocery Total
Ravi buys rice for ₹80, oil for ₹150, and sugar for ₹50.
- Calculate the total amount.
- Calculate a 5% discount.
- Find the final amount.
Expected final amount: ₹266.
Intermediate Exercise: Discount Eligibility
A grocery shop offers a discount when the bill reaches ₹1,000. Members also qualify for a separate offer.
- Create a variable for the bill amount.
- Create a boolean variable for membership.
- Use comparison and logical operators.
- Print whether the customer qualifies.
Hint: Use >= and &&.
Advanced Exercise: Payment Validation
A customer can complete payment when the amount is positive. The payment must also use cash or UPI.
- Store the payment amount.
- Store the payment method.
- Check the amount using a comparison operator.
- Combine the conditions using logical operators.
- Print the final payment status.
Hint: Use >, ===, and ||.
15. Quick Revision
| Category | Operators | Main purpose |
|---|---|---|
| Arithmetic | +, -, *, /, %, **, ++, -- | Perform calculations |
| Comparison | ==, ===, !=, !==, >, <, >=, <= | Compare values |
| Logical | &&, ||, ! | Combine or reverse conditions |
16. Next Steps and Community
Explore Further
Continue learning JavaScript by practising conditions and expressions. Try writing small programs using real business rules.
Useful official reference: MDN – Expressions and Operators.
Share Your Knowledge
Have a different way to solve these exercises? Share your code and explain your approach. Your examples can help other learners understand JavaScript better.
Learn Technology. Build Your Future.
Keep practising. Small programs build strong JavaScript skills.