Operators & Expressions in JavaScript
Learn how to perform calculations, compare values, and build expressions in JavaScript.
Prerequisites: Before starting this tutorial, we recommend completing the Variables & Data Types tutorial to understand the concepts used here.
🎯 🧮 Calculating Every Check
Before the dining room opens, managers run numbers: expected guests, revenue goals, discounts, and staffing needs. Every decision relies on operators—add, compare, and evaluate data quickly so the night runs smoothly.
- When was the last time you split a bill or calculated a tip in your head?
- How do you currently compare options (prices, routes, schedules) when making decisions?
- Which everyday rules could be expressed as AND/OR logic?
Mastering JavaScript operators gives you the mental calculator needed to build responsive UI, pricing tools, and decision logic throughout the rest of this series.
Learning Objectives
By the end of this lesson, you'll be able to:
- ✓ Use arithmetic operators to model totals, discounts, and remainders
- ✓ Choose strict versus loose comparison operators to avoid coercion bugs
- ✓ Combine conditions with logical AND/OR/NOT to mirror business rules
- ✓ Apply Apply assignment operators to update state efficiently
- ✓ Explain Explain operator precedence and control it with parentheses
- ✓ Practice short interactive examples using the browser console
Why This Matters:
These objectives focus your practice so operators become everyday tools rather than syntax to memorize.
What are Operators?
Operators are symbols that perform operations on values and variables. Think of them as the verbs of programming - they're what makes things happen!
In our restaurant analogy, operators are like the cooking instructions in a recipe. They tell the chef (JavaScript) what to do with the ingredients (variables and values).
Types of Operators in JavaScript
We'll explore each of these operator types in detail, with examples relevant to our restaurant theme.
⏸️ Checkpoint: Operator Strategy
Before moving forward, can you answer these?
- Which operator family would you reach for to implement a loyalty discount?
- How do you decide between == and === in new code?
- Where could a logical OR save repeated if statements in your project?
Tips to Remember:
- Write expressions in plain language first, then map them to symbols.
- Prefer strict equality to prevent hidden type coercion.
- Group related updates with compound assignment to stay readable.
How confident are you with this concept?
😕 Still confused | 🤔 Getting there | 😊 Got it! | 🎉 Could explain it to a friend!
Arithmetic Operators
Arithmetic operators perform mathematical calculations on numbers. They're essential for any calculations in your code.
| Operator | Name | Purpose | Example |
|---|---|---|---|
+ | Addition | Adds numbers together | 5 + 3 equals 8 |
- | Subtraction | Subtracts the right number from the left | 10 - 4 equals 6 |
* | Multiplication | Multiplies numbers together | 3 * 4 equals 12 |
/ | Division | Divides the left number by the right | 12 / 3 equals 4 |
% | Modulus (Remainder) | Returns the division remainder | 10 % 3 equals 1 |
** | Exponentiation | Raises to the power of | 2 ** 3 equals 8 |
++ | Increment | Increases a value by 1 | let x = 5; x++; makes x equal 6 |
-- | Decrement | Decreases a value by 1 | let x = 5; x--; makes x equal 4 |
Arithmetic Operations Visualized
Let's visualize how arithmetic operators work in a restaurant context:
Addition (+)
Adding items to a customer's bill
Multiplication (*)
Calculating cost for multiple items
Division (/)
Splitting the bill among friends
Warning: Division by Zero
In JavaScript (and mathematics in general), dividing by zero is not allowed and will result in Infinity or -Infinity. For example:
let result = 10 / 0; // Results in Infinity
let negResult = -10 / 0; // Results in -InfinityThis won't crash your program, but it can lead to unexpected behavior. Always check that your divisor is not zero before performing division:
// Safe division example
function safeDivide(numerator, denominator) {
if (denominator === 0) {
console.error("Cannot divide by zero!");
return null;
}
return numerator / denominator;
}In our restaurant analogy, this would be like trying to split a bill among zero people - it simply doesn't make sense!
Modulus (%)
Finding extra seats needed for a party
Understanding the Modulus Operator (%)
The modulus operator (%) might be new to you if you haven't seen it in math class. It returns the remainder after division.
How It Works:
10 % 3 = 1(10 divided by 3 equals 3 with a remainder of 1)8 % 4 = 0(8 divided by 4 equals 2 with no remainder)7 % 2 = 1(7 divided by 2 equals 3 with a remainder of 1)
Common Uses:
- Checking if a number is even or odd:
x % 2 === 0(even if true) - Cycling through a range (like hours on a clock):
hour % 12 - Determining if a number is divisible by another:
x % y === 0
In our restaurant example, we might use the modulus operator to:
Restaurant Examples
Special note about +: The + operator can also be used to concatenate (join) strings. For example, "Hello" + " World" results in "Hello World".
Order of Operations
JavaScript follows the standard mathematical order of operations, known as PEMDAS (in the US) or BEDMAS (in many other countries):
- Parentheses / Brackets:
() - Exponents / Exponentiation:
** - Multiplication and Division:
*,/,% - Addition and Subtraction:
+,-
Example: 2 + 3 * 4 equals 14 (not 20) because multiplication happens before addition.
If you want to change the order, use parentheses/brackets: (2 + 3) * 4 equals 20.
Note: You might have learned this as PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction) or BEDMAS (Brackets, Exponents, Division/Multiplication, Addition/Subtraction). Both are correct and refer to the same order of operations.
Try It Yourself
Let's practice using operators with some real-world examples. Open your browser's console (F12 or right-click → Inspect → Console) and try these calculations:
Restaurant Bill Calculator
Tip Calculator
Pro Tip: Use the console to experiment with different values and operators. Try modifying the examples above with your own numbers!
Comparison Operators
Comparison operators compare two values and return a boolean result (true or false). They're essential for making decisions in your code.
| Operator | Name | Purpose | Example |
|---|---|---|---|
== | Equal to (value) | Tests if values are equal | 5 == "5" is true |
=== | Strictly equal to (value and type) | Tests if values and types are equal | 5 === "5" is false |
!= | Not equal to (value) | Tests if values are not equal | 5 != "6" is true |
!== | Strictly not equal to (value and type) | Tests if values or types are not equal | 5 !== "5" is true |
> | Greater than | Tests if left value is greater than right | 10 > 5 is true |
< | Less than | Tests if left value is less than right | 5 < 10 is true |
>= | Greater than or equal to | Tests if left value is greater than or equal to right | 10 >= 10 is true |
<= | Less than or equal to | Tests if left value is less than or equal to right | 5 <= 5 is true |
Important: == vs ===
== (Double Equals)
Compares values only
Performs type conversion
Less strict, more forgiving
=== (Triple Equals)
Compares values AND types
No type conversion
More strict, safer
Best Practice: Use === (and !==) by default to avoid unexpected behavior.
Comparison Operators Visualized
Let's visualize how comparison operators work using restaurant prices:
Greater Than (>)
$29.99 > $18.99 is true
Less Than or Equal To (<=)
$24.99 <= $24.99 is true
Comparison Truth Table
| Expression | Result | Visual | Explanation |
|---|---|---|---|
5 > 3 | true | 5 is greater than 3 | |
5 < 3 | false | 5 is not less than 3 | |
5 >= 5 | true | 5 is equal to 5 | |
5 === "5" | false | Different types (number vs string) |
Restaurant Analogy: Comparison operators are like checking reservations. Is this table for more than 4 people? Is the customer's budget less than or equal to $50? These comparisons help make decisions about seating, menu recommendations, and more.
Restaurant Examples
Note: Comparison operators are essential for conditional statements (if/else), which we'll cover in the Control Flow tutorial.
Logical Operators
Logical operators combine multiple conditions and return a boolean result. They're used to make complex decisions based on multiple factors.
| Operator | Name | Purpose | Example |
|---|---|---|---|
&& | Logical AND | Returns true if both conditions are true | true && true is truetrue && false is false |
|| | Logical OR | Returns true if at least one condition is true | true || false is truefalse || false is false |
! | Logical NOT | Inverts a boolean value | !true is false!false is true |
Logical Operators Visualized
Let's visualize how logical operators work using Venn diagrams and circuit diagrams:
Venn Diagrams
AND (&&)
OR (||)
NOT (!)
Circuit Diagrams
AND Circuit
Both inputs must be true for the output to be true
OR Circuit
At least one input must be true for the output to be true
Restaurant Analogy: Logical operators are like restaurant policies. A customer can order from the special menu if they are vegetarian AND don't have allergies. A customer should expect to wait if it's the weekend OR they don't have a reservation.
Restaurant Examples
Truth Tables
AND (&&)
| A | B | A && B |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
OR (||)
| A | B | A || B |
|---|---|---|
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
NOT (!)
| A | !A |
|---|---|
| true | false |
| false | true |
Assignment Operators
Assignment operators assign values to variables. They're used to set or update variable values.
| Operator | Name | Purpose | Example | Equivalent to |
|---|---|---|---|---|
= | Assignment | Assigns a value to a variable | x = 10 | x = 10 |
+= | Addition assignment | Adds and assigns | x += 5 | x = x + 5 |
-= | Subtraction assignment | Subtracts and assigns | x -= 3 | x = x - 3 |
*= | Multiplication assignment | Multiplies and assigns | x *= 2 | x = x * 2 |
/= | Division assignment | Divides and assigns | x /= 4 | x = x / 4 |
%= | Remainder assignment | Gets remainder and assigns | x %= 3 | x = x % 3 |
Restaurant Examples
Assignment Operators Visualized
Let's visualize how assignment operators change variable values:
Before and After Visualization
Basic Assignment (=)
Creating a new variable and assigning a value
Addition Assignment (+=)
Adding to an existing value (bill = bill + 12)
Multiplication Assignment (*=)
Applying a 10% discount (bill = bill * 0.9)
Division Assignment (/=)
Splitting the bill between 2 people (bill = bill / 2)
Container Metaphor
Variables as Containers
Variables store values that can be modified with assignment operators
Restaurant Analogy: Assignment operators are like updating a customer's bill throughout their meal. You start with an initial amount, add items (+=), apply discounts (*=), split the bill (/=), and calculate the final total.
Tip: Assignment operators are shortcuts that make your code more concise. They're especially useful when you need to update a variable based on its current value.
Practice Exercises
Let's practice using operators with real-world scenarios from our restaurant theme:
Exercise 1: Menu Price Calculator
Calculate the total price for a customer's order:
Exercise 2: Table Assignment
Use the modulus operator to assign tables to parties:
Exercise 3: Discount Calculator
Calculate discounts based on conditions:
Exercise 4: Split Bill Calculator
Calculate individual shares when splitting the bill:
Pro Tips:
- Use the browser's console to experiment with different values
- Try combining different operators to solve more complex problems
- Pay attention to operator precedence when combining operations
- Use parentheses to make your calculations clearer
Challenge Yourself
Try these additional challenges to test your understanding:
- Calculate the average bill amount for a table of customers
- Determine if a reservation time falls within operating hours
- Calculate the most efficient table arrangement for a large party
- Implement a loyalty points system using arithmetic operators
Setup
You can practice this exercise in two ways:
- Browser Console:
- Open your browser's DevTools (F12 or Cmd+Option+I)
- Go to the Console tab
- Type or paste the code directly
- HTML File:
- Create a new file called
practice.html - Add this basic structure:
- Create a new file called
Challenge: Black Swan Bistro Bill Calculator
Create a program that calculates a restaurant bill with tax and tip:
Hints
- Use arithmetic operators to calculate subtotal, tax, and tip
- Use comparison operators to check if the customer is eligible for a discount
- Use logical operators to combine multiple conditions
- Use assignment operators to update variables efficiently
Solution
Lesson checkpoint
Test Your Knowledge
Strengthen your understanding of Operators by answering the quiz below.
Operators Quiz
Test your understanding of Operators concepts.
Lesson Complete: What You Learned
Key Takeaways:
- Arithmetic operators (+, -, *, /, %) perform calculations on numbers
- Comparison operators (===, !==, <, >, <=, >=) return true or false
- Always prefer strict equality (===) over loose equality (==) to avoid type coercion bugs
- Logical operators (&&, ||, !) combine or invert boolean conditions
- Compound assignment operators (+=, -=, *=) provide concise update syntax
- Operator precedence determines evaluation order; use parentheses to be explicit
Learning Objectives Review:
Look back at what you set out to learn. Can you now:
- ✅ Use arithmetic operators to model totals, discounts, and remainders Check!
- ✅ Choose strict versus loose comparison operators to avoid coercion bugs Got it!
- ✅ Combine conditions with logical AND/OR/NOT to mirror business rules Can explain it!
- ✅ Apply assignment operators to update state efficiently Could teach this!
- ✅ Explain operator precedence and control it with parentheses Check!
- ✅ Practice short interactive examples using the browser console Got it!
If you can confidently answer "yes" to most of these, you're ready to move on!
Think & Reflect:
Practical Calculations
- Which arithmetic operators would you combine to build a tip calculator?
- How does the modulo operator help with alternating row styles or pagination?
Comparisons & Logic
- Why does strict equality prevent subtle bugs that loose equality allows?
- How would you express a multi-condition filter using logical operators?
🤔 Real-World Test:
Operators are at the heart of every interactive feature on the web. E-commerce sites use arithmetic operators to calculate totals and discounts. Login systems use comparison operators to validate credentials. Search filters use logical operators to combine multiple criteria. Mastering operators means you can build the decision-making logic behind any application.
🎯 Looking Ahead:
Now that you can perform calculations and comparisons, you're ready to learn about conditionals. In the next lesson, you'll use if statements, switch cases, and ternary operators to make your programs respond differently based on conditions—bringing true decision-making to your code.
Recommended Next Steps
Related Topics
Explore these related tutorials to expand your knowledge:
Practice Projects
Apply what you've learned with these hands-on projects:
Additional Resources
Deepen your understanding with these helpful resources:
- MDN: Expressions and operators - Complete guide to JavaScript operators
Progress tracking is disabled. Enable it in to track your completed tutorials.
Cookie Settings