Beginner30 minutesJavaScriptLevel 3

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.

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

Operators Arithmetic Comparison Logical Assignment Other

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?

  1. Which operator family would you reach for to implement a loyalty discount?
  2. How do you decide between == and === in new code?
  3. 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.

OperatorNamePurposeExample
+AdditionAdds numbers together5 + 3 equals 8
-SubtractionSubtracts the right number from the left10 - 4 equals 6
*MultiplicationMultiplies numbers together3 * 4 equals 12
/DivisionDivides the left number by the right12 / 3 equals 4
%Modulus (Remainder)Returns the division remainder10 % 3 equals 1
**ExponentiationRaises to the power of2 ** 3 equals 8
++IncrementIncreases a value by 1let x = 5; x++; makes x equal 6
--DecrementDecreases a value by 1let x = 5; x--; makes x equal 4

Arithmetic Operations Visualized

Let's visualize how arithmetic operators work in a restaurant context:

Addition (+)

$24.99 Salmon + $18.99 Pasta = $43.98 Total

Adding items to a customer's bill

Multiplication (*)

$9.99 Wine × 3 Glasses = $29.97 Total

Calculating cost for multiple items

Division (/)

$120 Bill ÷ 4 People = $30 Per Person

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 -Infinity

This 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 (%)

11 People % 4 Per Table = 3 Extra Seats

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):

  1. Parentheses / Brackets: ()
  2. Exponents / Exponentiation: **
  3. Multiplication and Division: *, /, %
  4. Addition and Subtraction: +, -
Parentheses/Brackets () Exponents ** Multiplication * / % Addition + -

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.

OperatorNamePurposeExample
==Equal to (value)Tests if values are equal5 == "5" is true
===Strictly equal to (value and type)Tests if values and types are equal5 === "5" is false
!=Not equal to (value)Tests if values are not equal5 != "6" is true
!==Strictly not equal to (value and type)Tests if values or types are not equal5 !== "5" is true
>Greater thanTests if left value is greater than right10 > 5 is true
<Less thanTests if left value is less than right5 < 10 is true
>=Greater than or equal toTests if left value is greater than or equal to right10 >= 10 is true
<=Less than or equal toTests if left value is less than or equal to right5 <= 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 true

$29.99 > $18.99 is true

Less Than or Equal To (<=)

$24.99 $24.99 true

$24.99 <= $24.99 is true

Comparison Truth Table

ExpressionResultVisualExplanation
5 > 3true 5 > 3 5 is greater than 3
5 < 3false 5 < 3 5 is not less than 3
5 >= 5true 5 5 5 is equal to 5
5 === "5"false 5 "5" 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.

OperatorNamePurposeExample
&&Logical ANDReturns true if both conditions are truetrue && true is true
true && false is false
||Logical ORReturns true if at least one condition is truetrue || false is true
false || false is false
!Logical NOTInverts a boolean value!true is false
!false is true
AND (&&) A B A && B Both must be true OR (||) A B A || B At least one must be true NOT (!) A !A Inverts the value

Logical Operators Visualized

Let's visualize how logical operators work using Venn diagrams and circuit diagrams:

Venn Diagrams

AND (&&)
A isVegetarian B !hasAllergies A && B Only the intersection is true
OR (||)
A isWeekend B !hasReservation A || B The entire area is true
NOT (!)
Universe (all possible values) A isWeekend !A (everything outside A)

Circuit Diagrams

AND Circuit
isVegetarian !hasAllergies AND true

Both inputs must be true for the output to be true

OR Circuit
isWeekend !hasReservation OR true

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 (&&)

ABA && B
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

OR (||)

ABA || B
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

NOT (!)

A!A
truefalse
falsetrue

Assignment Operators

Assignment operators assign values to variables. They're used to set or update variable values.

OperatorNamePurposeExampleEquivalent to
=AssignmentAssigns a value to a variablex = 10x = 10
+=Addition assignmentAdds and assignsx += 5x = x + 5
-=Subtraction assignmentSubtracts and assignsx -= 3x = x - 3
*=Multiplication assignmentMultiplies and assignsx *= 2x = x * 2
/=Division assignmentDivides and assignsx /= 4x = x / 4
%=Remainder assignmentGets remainder and assignsx %= 3x = x % 3

Restaurant Examples

Assignment Operators Visualized

Let's visualize how assignment operators change variable values:

Before and After Visualization

Basic Assignment (=)
bill undefined bill = 50 bill 50

Creating a new variable and assigning a value

Addition Assignment (+=)
bill 50 bill += 12 bill 62

Adding to an existing value (bill = bill + 12)

Multiplication Assignment (*=)
bill 70 bill *= 0.9 bill 63

Applying a 10% discount (bill = bill * 0.9)

Division Assignment (/=)
bill 63 bill /= 2 bill 31.5

Splitting the bill between 2 people (bill = bill / 2)

Container Metaphor

Variables as Containers
bill $50 Initial: $62 += 12: $55.80 *= 0.9: tip $11.16 = bill * 0.2: $66.96 bill += tip:

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:

  1. Calculate the average bill amount for a table of customers
  2. Determine if a reservation time falls within operating hours
  3. Calculate the most efficient table arrangement for a large party
  4. Implement a loyalty points system using arithmetic operators

Setup

You can practice this exercise in two ways:

  1. Browser Console:
    • Open your browser's DevTools (F12 or Cmd+Option+I)
    • Go to the Console tab
    • Type or paste the code directly
  2. HTML File:
    • Create a new file called practice.html
    • Add this basic structure:

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

3 questions

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

Operators are the building blocks of every formula in your applications. Practising with real scenarios like pricing and discounts cements their use.
  • 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

Clear, predictable comparisons are the foundation of conditionals and loops. Building the habit of strict equality now saves debugging time in every future project.
  • 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

Continue Learning

Ready to move forward? Continue with the next tutorial in this series:

Conditionals

Related Topics

Explore these related tutorials to expand your knowledge:

Practice Projects

Apply what you've learned with these hands-on projects:

Calculator App

Build a basic calculator with arithmetic operators

JavaScriptOperatorsMath
Start Project

Grade Calculator

Create a tool to calculate final grades

JavaScriptOperatorsLogic
Start Project

Additional Resources

Deepen your understanding with these helpful resources:

Progress tracking is disabled. Enable it in to track your completed tutorials.