Skip to main content

โšก Lesson 4: Operators & Expressions

Learn how to perform calculations, make comparisons, and combine logic โ€” the tools that make your programs make decisions.

๐ŸŽฏ Learning Objectives

By the end of this lesson, you will be able to:

  • Use arithmetic operators for math calculations
  • Apply assignment operators including shorthand (+=, -=, etc.)
  • Compare values with ==, ===, !=, !==, <, >
  • Explain the critical difference between == and ===
  • Combine conditions with logical operators (&&, ||, !)
  • Understand operator precedence and how expressions evaluate

Estimated Time: 45 minutes

Project: Build a tip calculator using operators

In This Lesson

Introduction

Variables let you store data. Operators let you actually do something with it: add up a shopping cart, check whether a password is long enough, or decide if a visitor gets a discount. Put values and operators together and you get an expression โ€” any piece of code that works out to a value. 2 + 3 is an expression that produces 5.

By the end of this lesson you'll use these building blocks to make a working tip calculator โ€” and you'll be ready to teach your code to make decisions in Module 2.

Arithmetic Operators

These perform math on numbers, just like a calculator.

Operator Name Example Result
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division10 / 33.333...
%Modulo (remainder)10 % 31
**Exponentiation2 ** 38

let price = 29.99;
let quantity = 3;
let subtotal = price * quantity;
console.log(`Subtotal: $${subtotal}`);  // "Subtotal: $89.97"

// Modulo is great for checking even/odd
let number = 7;
console.log(number % 2);  // 1 (odd โ€” remainder when dividing by 2)
console.log(8 % 2);       // 0 (even)

// Increment and Decrement
let count = 5;
count++;  // count is now 6 (same as count = count + 1)
count--;  // count is now 5 again
                

๐Ÿ’ก Modulo (%) Use Cases

Modulo gives you the remainder after division. Common uses include checking if a number is even (n % 2 === 0), wrapping around values (like cycling through array indices), and converting total seconds into minutes/seconds.

Assignment Operators

You already know = assigns a value. Shorthand operators combine assignment with an operation.

Operator Example Equivalent To
=x = 10Assign 10 to x
+=x += 5x = x + 5
-=x -= 3x = x - 3
*=x *= 2x = x * 2
/=x /= 4x = x / 4
%=x %= 3x = x % 3
**=x **= 2x = x ** 2

let score = 100;
score += 25;   // score is now 125
score -= 10;   // score is now 115
score *= 2;    // score is now 230

console.log(score);  // 230
                

Comparison Operators

Comparison operators compare two values and return a boolean (true or false). They're the foundation of decision-making in code.

Operator Name Example Result
===Strict equal5 === 5true
!==Strict not equal5 !== "5"true
==Loose equal5 == "5"true
!=Loose not equal5 != "5"false
>Greater than10 > 5true
<Less than3 < 7true
>=Greater or equal5 >= 5true
<=Less or equal3 <= 2false

The Critical Difference: === vs. ==

This is one of the most important things to understand in JavaScript.


// === (strict equality) โ€” checks value AND type
console.log(5 === 5);      // true  (same value, same type)
console.log(5 === "5");    // false (same value, different type!)
console.log(true === 1);   // false (different types)

// == (loose equality) โ€” converts types before comparing
console.log(5 == "5");     // true  (JS converts "5" to 5, then compares)
console.log(true == 1);    // true  (JS converts true to 1)
console.log(null == undefined);  // true (special case)
console.log("" == 0);      // true  (JS converts "" to the number 0)
                

โŒ Always Use === and !==

Loose equality (==) performs type coercion and produces counterintuitive results. Always use strict equality (===) and strict inequality (!==) unless you have a specific reason not to. This is a universal JavaScript best practice.


// Why == is dangerous โ€” most of these are surprising!
console.log("" == 0);           // true
console.log("0" == 0);          // true
console.log("" == "0");         // false (both strings, no coercion)
console.log(false == "0");      // true
console.log(false == "");       // true
console.log(null == undefined); // true

// With ===, the results make sense
console.log("" === 0);          // false
console.log("0" === 0);         // false
console.log(false === "0");     // false
                

Logical Operators

Logical operators combine boolean values or expressions. They're how you build complex conditions.

Operator Name Description Example Result
&&ANDBoth must be truetrue && truetrue
||ORAt least one must be truefalse || truetrue
!NOTFlips the value!truefalse

let age = 25;
let hasID = true;

// AND โ€” both conditions must be true
let canEnter = age >= 21 && hasID;
console.log(canEnter);  // true

// OR โ€” at least one condition must be true
let isWeekend = false;
let isHoliday = true;
let dayOff = isWeekend || isHoliday;
console.log(dayOff);  // true

// NOT โ€” flips the boolean
let isLoggedIn = false;
console.log(!isLoggedIn);  // true (NOT false = true)

// Combining them
let isMember = true;
let hasCoupon = false;
let getsDiscount = isMember || hasCoupon;
let canCheckout = getsDiscount && age >= 18;
console.log(`Gets discount: ${getsDiscount}`);   // true
console.log(`Can checkout: ${canCheckout}`);       // true
                

๐Ÿ’ก Short-Circuiting

&& and || stop as soon as they know the answer. With &&, if the left side is false, the right side is never even checked. With ||, if the left side is true, the right side is skipped. Also, with non-boolean values they return one of the original values rather than true/false: "Ray" || "Guest" gives "Ray", and "" || "Guest" gives "Guest". You'll use that trick for default values in Module 2.

graph TD A["age >= 21?"] -->|Yes| B["hasID?"] A -->|No| D["โŒ Cannot Enter"] B -->|Yes| C["โœ… Can Enter"] B -->|No| D style C fill:#ecfdf5,stroke:#22c55e,stroke-width:2px,color:#1e293b style D fill:#fef2f2,stroke:#ef4444,stroke-width:2px,color:#1e293b

Truthy and Falsy Values

JavaScript can treat non-boolean values as true or false in logical contexts. These are called truthy and falsy values.


// Falsy values (these all evaluate to false):
// false, 0, -0, 0n (BigInt zero), "", null, undefined, NaN

// Everything else is truthy:
// true, any number (except 0 and NaN), any non-empty string, objects, arrays
// (even empty ones: [] and {} are truthy!)

console.log(Boolean(0));          // false
console.log(Boolean(""));         // false
console.log(Boolean(null));       // false
console.log(Boolean(undefined));  // false

console.log(Boolean(1));          // true
console.log(Boolean("hello"));    // true
console.log(Boolean(42));         // true
console.log(Boolean("0"));        // true (non-empty string!)
                

โš ๏ธ Common Gotcha

"0" (the string containing zero) is truthy because it's a non-empty string. 0 (the number zero) is falsy. This catches many beginners off guard.

String Operators

The + operator does double duty โ€” it adds numbers and concatenates (joins) strings.


// Concatenation
let first = "Java";
let second = "Script";
let combined = first + second;
console.log(combined);  // "JavaScript"

// Concatenation with variables
let greeting = "Hello, " + "World!";
console.log(greeting);  // "Hello, World!"

// += works with strings too
let message = "Good";
message += " morning!";
console.log(message);  // "Good morning!"
                

โœ… Prefer Template Literals

For building strings with variables, template literals (backticks) are cleaner than + concatenation. You learned this in Lesson 3 โ€” keep using them!

Operator Precedence

When an expression has multiple operators, JavaScript follows a specific order โ€” just like math class (PEMDAS/BODMAS). Key points:

  1. Parentheses () โ€” evaluated first (always use these to be explicit!)
  2. Exponentiation **
  3. Multiplication / Division / Modulo * / %
  4. Addition / Subtraction + -
  5. Comparisons < > <= >=
  6. Equality === !== == !=
  7. Logical AND &&
  8. Logical OR ||
  9. Assignment = += -= etc.

// Without parentheses โ€” follows precedence rules
let result = 2 + 3 * 4;
console.log(result);  // 14 (not 20! multiplication first)

// With parentheses โ€” explicit and clear
let result2 = (2 + 3) * 4;
console.log(result2);  // 20

// Complex expression
let total = 100 - 20 * 0.1 + 5;
console.log(total);  // 103 (20 * 0.1 = 2, then 100 - 2 + 5)

// Clear version with parentheses
let total2 = (100 - (20 * 0.1)) + 5;
console.log(total2);  // 103 (same result, but intention is clear)
                

โœ… Pro Tip: Use Parentheses Generously

Don't rely on memorizing precedence rules. Use parentheses to make your intentions clear. Future you (and anyone reading your code) will thank you.

Hands-on Exercise

๐Ÿ‹๏ธ Exercise: Tip Calculator

Objective: Use arithmetic, assignment, and comparison operators to build a console-based tip calculator.

Instructions:


// Tip Calculator

// TODO: Set up these variables
// const billAmount = 85.50;
// const tipPercentage = 20;  // 20%
// const numberOfPeople = 3;

// TODO: Calculate:
// 1. tipAmount (billAmount * tipPercentage / 100)
// 2. totalWithTip (billAmount + tipAmount)
// 3. perPerson (totalWithTip / numberOfPeople)

// TODO: Log the results using template literals
// "Bill: $85.50"
// "Tip (20%): $17.10"
// "Total: $102.60"
// "Per person: $34.20"

// BONUS: Check if the bill is "expensive" (over $100 after tip)
// Log whether it is using a comparison
                    
๐Ÿ’ก Hint

Use .toFixed(2) on numbers to format them to two decimal places: perPerson.toFixed(2) gives you the string "34.20" instead of 34.199999999999996. (That long number isn't a bug in your code โ€” computers store decimals in binary, so tiny rounding errors are normal. Always format money with .toFixed(2) when you display it.)

โœ… Solution

const billAmount = 85.50;
const tipPercentage = 20;
const numberOfPeople = 3;

const tipAmount = billAmount * tipPercentage / 100;
const totalWithTip = billAmount + tipAmount;
const perPerson = totalWithTip / numberOfPeople;

console.log(`Bill: $${billAmount.toFixed(2)}`);
console.log(`Tip (${tipPercentage}%): $${tipAmount.toFixed(2)}`);
console.log(`Total: $${totalWithTip.toFixed(2)}`);
console.log(`Per person: $${perPerson.toFixed(2)}`);

// Bonus: Check if expensive
const isExpensive = totalWithTip > 100;
console.log(`Expensive? ${isExpensive}`);  // true
                        

๐ŸŽฏ Quick Quiz

Question 1: What does 10 % 3 return?

Question 2: What does 5 === "5" return?

Question 3: What is the result of true && false || true?

Question 4: After this code runs, what is the value of points?

let points = 10;
points += 5;
points *= 2;

Question 5: Which of these values is truthy?

๐Ÿ““ Learning Journal

Take five minutes to add to your learning journal. Write down:

  • Key concepts you learned
  • What clicked โ€” the idea or technique that made sense
  • Questions or confusion, so you know what to revisit
  • Ideas to try on your own pages
  • How you feel about your progress

โœ๏ธ This lesson's prompt: Before running them, predict what "5" + 3, "5" - 3, 5 == "5", and 5 === "5" will give you, and write down why. Then check your predictions in the console. Which one surprised you? In your own words, explain why this course tells you to always use ===. Finally, think of a rule on your own site you could write with && or || (for example, "show the banner if it's the weekend OR a holiday") โ€” what's still confusing about combining conditions?

Summary

๐ŸŽ‰ Key Takeaways

  • Arithmetic operators: +, -, *, /, %, ** for math
  • Assignment shorthand: +=, -=, *=, /= for cleaner updates
  • Always use === (strict equality) and !== instead of == and !=
  • Logical operators: && (AND), || (OR), ! (NOT) combine conditions
  • Truthy/falsy: false, 0, "", null, undefined, NaN are falsy; everything else is truthy
  • Use parentheses to make operator precedence clear and intentional

๐Ÿ“š Additional Resources

๐Ÿš€ What's Next?

You've completed Module 1! You now have the fundamentals: variables, data types, and operators. In Module 2, you'll learn to control the flow of your programs with conditionals โ€” making your code make decisions with if, else, and switch.

๐ŸŽ‰ Module 1 Complete!

You've finished JavaScript Foundations. You understand variables, data types, and operators. Time to make your code think!