Operators
In real life, we constantly perform operations. We add prices, compare values, and make decisions based on conditions.
JavaScript uses operators to perform these actions on data. They allow your program to calculate, compare, and decide.
What Is an Operator?
An operator is a special symbol that performs an operation on one or more values. Those values are called operands.
For example, adding two numbers or checking if one value is greater than another.
Why Operators Matter
Without operators, JavaScript would not be able to:
- Calculate totals
- Compare values
- Make decisions
- Control program flow
Almost every real-world application relies heavily on operators.
Arithmetic Operators
Arithmetic operators are used for mathematical calculations.
let total = 10 + 5;
let discount = 20 - 5;
let price = 10 * 3;
let average = 20 / 4;
let remainder = 10 % 3;
These operators are commonly used in shopping carts, billing systems, and score calculations.
Assignment Operators
Assignment operators are used to assign values to variables.
let count = 10;
count += 5;
count -= 2;
They make code shorter and easier to read.
Comparison Operators
Comparison operators compare two values and return a boolean
(true or false).
10 > 5;
10 < 5;
10 == "10";
10 === "10";
These operators are often used in conditions and validations.
Equality vs Strict Equality
JavaScript has two ways to compare equality:
- == compares values only
- === compares both value and data type
5 == "5"; // true
5 === "5"; // false
Using === avoids unexpected results and is considered best practice.
Logical Operators
Logical operators are used to combine conditions.
true && false;
true || false;
!true;
They are commonly used in login checks, form validation, and access control.
Real-World Example
Imagine checking if a user can place an order:
let isLoggedIn = true;
let hasBalance = true;
isLoggedIn && hasBalance;
Only when both conditions are true will the order proceed.
Thumb Rules
- Use arithmetic operators for calculations
- Prefer
===over== - Use logical operators to combine conditions
- Readable code is better than clever code
More on Operators Later
In this lesson, we focused on the most commonly used operators for beginners.
Some advanced operator behavior is intentionally kept for later lessons.
- Conditional logic using operators is covered in Lesson 6 (Conditions)
- Complex expressions and execution flow are explained in Lesson 43 (Execution Context)
What Comes Next?
Now that you understand operators, the next step is learning how JavaScript makes decisions.
In the next lesson, we will explore conditional statements.