Operators
Use operators to calculate, compare, assign, and combine values.
Operators and expressions are essential building blocks in JavaScript. They allow programs to perform calculations, compare values, make decisions, and manipulate data. Almost every JavaScript application uses operators and expressions to process information and produce results.
Think of operators as tools and expressions as complete tasks. Just as a calculator uses symbols like + and - to perform calculations, JavaScript uses operators to work with values and variables.
What Are Operators?
An operator is a special symbol that tells JavaScript to perform a specific action on one or more values.
let total = 10 + 5;In this example:
- 10 and 5 are operands.
- + is the operator.
- The result is 15.
Operators help JavaScript perform mathematical calculations, comparisons, and logical operations.
What Is an Expression?
An expression is any piece of code that produces a value.
10 + 5This expression evaluates to:
15Another example:
let age = 25;The expression 25 produces a value, which is then stored in age.
Arithmetic Operators
Arithmetic operators are used for mathematical calculations.
let a = 10;
let b = 5;
console.log(a + b); // Addition
console.log(a - b); // Subtraction
console.log(a * b); // Multiplication
console.log(a / b); // Division
console.log(a % b); // RemainderCommon arithmetic operators include +, -, *, /, and %.
Assignment Operators
Assignment operators are used to store values in variables.
let score = 100;The = operator assigns the value 100 to score.
JavaScript also provides shorthand assignment operators.
let points = 50;
points += 10;
console.log(points);Output:
60This is the same as writing:
points = points + 10;Comparison Operators
Comparison operators compare two values and return true or false.
let age = 18;
console.log(age >= 18);Output:
trueCommon comparison operators include ==, ===, !=, >, <, >=, and <=.
Logical Operators
Logical operators combine multiple conditions.
let age = 25;
let hasLicense = true;
console.log(age >= 18 && hasLicense);Output:
trueCommon logical operators include && for AND, || for OR, and ! for NOT.
These operators are commonly used in decision-making.
Real-World Example
Imagine an online shopping website.
let cartTotal = 1200;
let isMember = true;
let discountEligible = cartTotal > 1000 && isMember;
console.log(discountEligible);Output:
trueThe customer qualifies for a discount because both conditions are satisfied.
Summary
Operators are symbols that perform actions on values, while expressions are combinations of values and operators that produce a result. JavaScript provides different types of operators, including arithmetic, assignment, comparison, and logical operators. Understanding operators and expressions is important because they are used in calculations, decision-making, and almost every JavaScript program you build.