← Operators and Expressions for Web · Lesson 5 of 5

Module Four

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
1

Course Outline

Operators & Expressions for Web · Course Outline
⚙️ beginner course · 2026

Operators & Expressions for Web

⚡ arithmetic · logic · comparison · JavaScript 🧠 4 modules · hands-on
📚 This course contains 4 modules plus a final certification project.
🎯 level Beginner · web developers & students
⏳ duration 4 weeks · 4–6 hours / week
🛠️ tools Browser Console · VS Code · CodePen · Node.js
Module 1 Introduction to Operators & Expressions
Understand what operators and expressions are, and how they power every line of JavaScript.
  • What is an expression?
  • What is an operator?
  • Operands & values
  • Statements vs expressions
  • Operator precedence basics
  • Using the browser console
✓ outcome Identify operators and expressions in real JavaScript code
Module 2 Arithmetic & Assignment Operators
Master the operators used for math and assigning values in web applications.
  • Addition, subtraction, multiplication, division
  • Modulus (%) and exponent (**)
  • Increment (++) and decrement (--)
  • Assignment (=, +=, -=, *=, /=)
  • Operator precedence & grouping
  • Common math mistakes
✓ outcome Build a simple calculator using arithmetic and assignment operators
Module 3 Comparison, Logical & String Operators
Learn how to compare values, combine conditions, and work with text on the web.
  • Equal (==) vs strict equal (===)
  • Not equal (!=) and (!==)
  • Greater than, less than, and equal variants
  • Logical AND (&&), OR (||), NOT (!)
  • String concatenation & template literals
  • Truthy and falsy values
✓ outcome Write conditional logic and build dynamic greetings on a web page
Module 4 Advanced Operators & Certification Project
Explore ternary, nullish, optional chaining, and complete a real web-based project.
  • Ternary operator ( ? : )
  • Nullish coalescing (??)
  • Optional chaining (?.)
  • Spread ( ... ) and Rest ( ... )
  • typeof, instanceof, in operators
  • Bitwise operators (quick intro)
✓ outcome Complete a full web project using modern JavaScript operators

⚙️ certification project beginner

"Interactive Web Calculator & Form Validator" — build a small web app using HTML, CSS, and JavaScript that uses arithmetic, comparison, logical, ternary, and nullish operators to calculate values and validate a user form.

🎯 portfolio piece · peer review · certification


⚡ includes hands-on coding labs, browser console practice, and certification project preparation.
2

Module One

Operators & Expressions for Web – Module One

Module One: Introduction to Operators and Expressions – The Building Blocks of JavaScript

“Operators & Expressions for Web” – Learn how JavaScript thinks and calculates

Module Introduction

Welcome, young web coder! Have you ever wondered how a website knows that 2 + 2 = 4? Or how a login page knows your password is correct? The answer is operators and expressions.

Operators are the symbols that tell the computer what to do — like +, -, =, and >. Expressions are the little puzzles you build with those symbols, like 2 + 3 or age > 18. Every website you use — from Facebook to your school portal — uses them thousands of times.

In this module, we will learn what operators and expressions are, how they work, and how to use them in the browser. We will use JavaScript, the language of the web. By the end, you will understand the foundation of every line of code you will ever write.

Let’s begin!

Learning Objectives

After finishing this module, you will be able to:

  • Explain what an operator is in your own words.
  • Explain what an expression is in your own words.
  • Identify operands, values, and operators in code.
  • Tell the difference between a statement and an expression.
  • Understand the basics of operator precedence.
  • Open and use the browser console.
  • Type and run simple expressions in the console.
  • Give Nigerian examples of operators in real life.
  • Think like a programmer when reading expressions.
  • Complete a mini project and practical assignment.

Warm-up Story: Ada’s Shopping Calculator

Ada is 13 years old and lives in Lagos. Her mother runs a small provisions shop. One Saturday, Ada was helping at the shop. A customer came in and bought:

  • 2 bags of rice at ₦3,000 each
  • 1 bottle of oil at ₦1,500
  • 3 tins of milk at ₦800 each

Ada’s mother quickly wrote down the total on paper. Ada watched and thought, "This is exactly what operators do in JavaScript!"

She opened her laptop and typed in the browser console:

(2 * 3000) + 1500 + (3 * 800);
  

The console showed: 9900. Ada smiled. She had used the multiplication operator (*), the addition operator (+), and the grouping operator ( ) — all in one line.

She also typed:

let total = (2 * 3000) + 1500 + (3 * 800);
total > 5000 ? "Big sale!" : "Small sale";
  

The console replied: "Big sale!". Ada had used the greater than operator (>), the assignment operator (=), and even the ternary operator ( ? : ). Her mother was amazed.

From that day, Ada used JavaScript to help with the shop’s calculations. She learned that operators are everywhere — in business, at home, and on the web.

Moral of the story: Operators are the tools computers use to calculate and compare. Expressions are the little puzzles they solve. Once you understand them, you can make websites do almost anything.

Main Lessons

Lesson 1: What is an Operator?

Definition: An operator is a symbol that tells the computer to do something with values.

Why it is important: Every calculation, comparison, or decision uses operators.

Simple explanation: An operator is like a tool in a toolbox. Each tool does a specific job.

Real-life example: A bank adds interest with the + operator.

School example: A teacher adds scores with the + operator.

Home example: A family subtracts spending with the - operator.

Nigerian example: A trader multiplies price by quantity with the * operator.

Illustration:

  Operator = Tool

  +  add
  -  subtract
  *  multiply
  /  divide
  >  greater than
  =  assign
  

Mini summary: An operator is a symbol that tells the computer what to do.

Lesson 2: What is an Expression?

Definition: An expression is a piece of code that produces a value.

Why it is important: Every expression the computer reads becomes a value, like a number, text, or true/false.

Simple explanation: An expression is a mini puzzle that has one answer.

Real-life example: 2 + 3 is an expression. Its value is 5.

School example: score >= 50 is an expression. Its value is true or false.

Home example: price * 2 is an expression.

Nigerian example: quantity * unitPrice is an expression.

Illustration:

  Expression → Value

  2 + 3       → 5
  "a" + "b"   → "ab"
  5 > 3       → true
  

Mini summary: An expression is a piece of code that gives a value.

Lesson 3: Operands – The Values in an Expression

Definition: Operands are the values that an operator works on.

Why it is important: Operators need operands to do anything.

Simple explanation: Operands are the things. Operators are what you do to them.

Real-life example: In 5 + 3, 5 and 3 are operands.

School example: In mathScore + englishScore, both scores are operands.

Home example: In rent + food, both are operands.

Nigerian example: In price * quantity, both are operands.

Illustration:

  Operand Operator Operand
     5        +        3
     |                  |
  operand            operand
  

Mini summary: Operands are the values that operators work on.

Lesson 4: Values and Data Types

Definition: A value is any piece of data, like a number, text, or true/false.

Why it is important: Operators behave differently with different types.

Simple explanation: Values are the ingredients. Operators are the cooking methods.

Real-life example: A bank stores balances as numbers and names as text.

School example: A teacher stores scores as numbers and names as text.

Home example: A family stores a shopping list as text.

Nigerian example: A trader stores prices as numbers and product names as text.

Illustration:

  Common Types:

  Number:  42, 3.14
  String:  "Hello", "Ada"
  Boolean: true, false
  Null:    null
  Undefined: undefined
  

Mini summary: Values come in types: number, string, boolean, null, undefined.

Lesson 5: Statements vs Expressions

Definition: A statement is a full instruction. An expression is a piece that produces a value.

Why it is important: Knowing the difference helps you understand code structure.

Simple explanation: A statement is a full sentence. An expression is a phrase inside it.

Real-life example: "Pay ₦500" is a statement. "₦500" is an expression.

School example: "Write your name" is a statement. "Your name" is a value.

Home example: "Buy milk" is a statement. "milk" is a value.

Nigerian example: "Send the goods to Enugu" is a statement.

Illustration:

  Statement:   let total = 2 + 3;
  Expression:  2 + 3
  Statement:   if (score > 50) { ... }
  Expression:  score > 50
  

Mini summary: Statements are full instructions. Expressions are parts that give values.

Lesson 6: Why Expressions Matter on the Web

Definition: On the web, expressions control what users see and do.

Why it is important: Every button, form, and message uses expressions behind the scenes.

Simple explanation: Expressions are the "thinking" part of a website.

Real-life example: A bank login page checks if the password matches.

School example: A school portal checks if grades are above pass mark.

Home example: A shopping site calculates the cart total.

Nigerian example: A fintech app calculates transfer fees automatically.

Illustration:

  Website Flow:

  User types → Expression checks → Result shown 🎉
  

Mini summary: Expressions make websites think, calculate, and react.

Lesson 7: The Browser Console

Definition: The browser console is a tool that lets you type and run JavaScript directly.

Why it is important: It is a safe place to test expressions quickly.

Simple explanation: The console is like a notepad where the computer answers you back.

Real-life example: A developer tests new code in the console before using it on a site.

School example: A student tests 2 + 2 in the console.

Home example: A family calculates a bill in the console.

Nigerian example: A trader calculates the total price of goods in the console.

Illustration:

  Open Console:

  Chrome: Ctrl + Shift + J  (Windows)
          Cmd + Option + J  (Mac)
  Firefox: Ctrl + Shift + K
  Edge: Ctrl + Shift + J
  

Step-by-step:

  1. Open your browser.
  2. Press the shortcut keys.
  3. Click on the Console tab.
  4. Type a simple expression like 2 + 3.
  5. Press Enter.
  6. See the answer!

Mini summary: The browser console is your safe playground for testing expressions.

Lesson 8: Running Your First Expression

Definition: Running an expression means typing it and pressing Enter to see its value.

Why it is important: It is the first step to writing code.

Simple explanation: Like typing a question and getting an answer immediately.

Real-life example: A developer tests a calculation before adding it to a page.

School example: A student tests 10 * 5 in the console.

Home example: A family tests the total of the groceries.

Nigerian example: A trader tests the total price of 5 bags of rice.

Illustration:

  Console:

  > 2 + 3
  < 5

  > "Hello " + "Ada"
  < "Hello Ada"

  > 10 > 5
  < true
  

Step-by-step:

  1. Open the console.
  2. Type 2 + 3.
  3. Press Enter.
  4. See 5.
  5. Try more expressions like 10 * 10 and "a" + "b".

Mini summary: Typing expressions in the console gives immediate results.

Lesson 9: Variables – Giving Values a Name

Definition: A variable is a named container that holds a value.

Why it is important: Variables let you store and reuse values.

Simple explanation: It is like a labeled box. You put a value in and use it later.

Real-life example: A bank names a value "balance".

School example: A teacher names a value "mathScore".

Home example: A family names a value "shoppingTotal".

Nigerian example: A trader names a value "totalSales".

Illustration:

  let balance = 5000;
  let name = "Ada";
  let isOpen = true;
  

Step-by-step:

  1. Write let or const.
  2. Give the variable a name.
  3. Add =.
  4. Write the value.
  5. End with a semicolon ( ; ).

Mini summary: Variables hold values in named containers.

Lesson 10: Using Variables in Expressions

Definition: Variables can be used inside expressions just like regular values.

Why it is important: It lets you calculate using names instead of numbers.

Simple explanation: If the value inside the box is 5, the box name becomes 5 in the puzzle.

Real-life example: A bank adds interest using the variable balance.

School example: A teacher adds mathScore + englishScore.

Home example: A family calculates rent + food + transport.

Nigerian example: A trader calculates quantity * price.

Illustration:

  let a = 5;
  let b = 3;
  a + b;      // 8

  let price = 3000;
  let qty   = 2;
  price * qty;  // 6000
  

Mini summary: Variables can be used inside expressions to calculate values.

Lesson 11: Operator Precedence – Which Comes First?

Definition: Operator precedence is the order in which operators are calculated.

Why it is important: It decides the final value of an expression.

Simple explanation: Like a queue — some operators go first, others wait.

Real-life example: A bank calculates multiplication before addition.

School example: In math, multiplication is done before addition.

Home example: You weigh ingredients before mixing them.

Nigerian example: A trader prices items before calculating the total.

Illustration:

  2 + 3 * 4

  Step 1: 3 * 4 = 12
  Step 2: 2 + 12 = 14

  (2 + 3) * 4

  Step 1: 2 + 3 = 5
  Step 2: 5 * 4 = 20
  

Step-by-step:

  1. Do parentheses ( ) first.
  2. Then multiply (*) and divide (/).
  3. Then add (+) and subtract (-).
  4. Read left to right for equal priority.

Mini summary: Operator precedence decides which part of an expression is calculated first.

Lesson 12: Grouping with Parentheses

Definition: Parentheses ( ) group parts of an expression and force them to be calculated first.

Why it is important: They prevent confusion and bugs.

Simple explanation: Parentheses are the "do this first" sign.

Real-life example: A bank uses ( ) to calculate fees before interest.

School example: A student uses ( ) to add scores before averaging.

Home example: A family adds groceries before adding tax.

Nigerian example: A trader adds quantity costs before applying a discount.

Illustration:

  2 + 3 * 4     → 14
  (2 + 3) * 4   → 20

  Parentheses change the answer!
  

Mini summary: Parentheses tell JavaScript which part to calculate first.

Lesson 13: Common Mistakes in Expressions

Definition: Mistakes happen. Knowing them helps you avoid them.

Why it is important: A small mistake can give the wrong answer.

Simple explanation: Like typing a phone number wrong — you get the wrong person.

Real-life example: A bank uses the wrong operator and pays wrong interest.

School example: A teacher forgets parentheses and gets wrong averages.

Home example: A family miscounts a shopping total.

Nigerian example: A trader forgets multiplication and undercharges a customer.

Table of common mistakes:

MistakeWhat HappensHow to Fix
Forgetting parenthesesWrong answerAdd ( ) to group
Mixing numbers and stringsWrong resultUse the right type
Missing semicolonErrorAdd ; at the end
Using = instead of ===Assignment instead of checkUse === to compare
Wrong variable nameReferenceErrorCheck spelling
Dividing by zeroInfinityCheck the denominator

Mini summary: Common mistakes: missing parentheses, wrong types, missing semicolons.

Lesson 14: Best Practices for Expressions

Definition: Best practices are good habits that make your code clean and safe.

Why it is important: Good habits prevent bugs and help others read your code.

Simple explanation: Like keeping your desk tidy — easier to find things.

Real-life example: A bank writes clean code so any developer can understand it.

School example: A student writes neat notes for exams.

Home example: A family keeps a tidy shopping list.

Nigerian example: A business writes clear, simple code.

List of best practices:

  • Use clear variable names.
  • Use parentheses to make meaning clear.
  • Use === instead of ==.
  • Keep expressions short and simple.
  • Add spaces around operators for readability.
  • Use comments for tricky expressions.
  • Test expressions in the console first.
  • Check types with typeof.
  • Avoid confusing nested expressions.
  • Read error messages carefully.

Mini summary: Best practices: clear names, parentheses, and simple expressions.

Lesson 15: Putting It All Together – Your First Expression Toolkit

You now have a strong foundation in operators and expressions.

What you learned:

  • What an operator is
  • What an expression is
  • What operands and values are
  • Statements vs expressions
  • The browser console
  • Running expressions
  • Variables and expressions
  • Operator precedence
  • Grouping with parentheses
  • Common mistakes and best practices

Next steps: In Module Two, you will learn about arithmetic and assignment operators in depth.

Illustration:

  Your Learning Journey:

  Module 1: Foundations
       |
       V
  Module 2: Arithmetic & Assignment
       |
       V
  Module 3: Comparison & Logic
       |
       V
  Module 4: Advanced & Certification
       |
       V
  Web Operators Expert 🎉
  

Mini summary: You now understand the basics of operators and expressions. Time to go deeper!

Key Vocabulary

WordSimple Definition
OperatorA symbol that tells the computer what to do.
ExpressionA piece of code that produces a value.
OperandA value that an operator works on.
ValueAny piece of data (number, text, etc.).
TypeThe kind of value (number, string, boolean).
StatementA full instruction in code.
VariableA named container for a value.
PrecedenceThe order operators are calculated.
ParenthesesSymbols ( ) that group parts of an expression.
ConsoleA tool for testing JavaScript.
NumberA numeric value, like 5 or 3.14.
StringA text value, like "Hello".
BooleanA true or false value.
NullA special value meaning "nothing".
UndefinedA value that has not been set.

Important Concepts

  • Operators are tools: They do specific jobs.
  • Expressions give values: Every expression has one answer.
  • Operands are values: Operators work on them.
  • Types matter: Numbers, strings, booleans behave differently.
  • Statements are full instructions: Expressions are parts of them.
  • The console is your playground: Test expressions there.
  • Variables hold values: Use them in expressions.
  • Precedence decides order: Multiplication before addition.
  • Parentheses override precedence: Use them for clarity.
  • Best practices prevent bugs: Write clean, clear code.

Step-by-step Explanations

How to open the browser console step by step

  1. Open Chrome, Edge, or Firefox.
  2. Press Ctrl + Shift + J (Windows) or Cmd + Option + J (Mac).
  3. Click the "Console" tab if it is not already open.
  4. Start typing JavaScript.

How to run an expression step by step

  1. Type a simple expression like 2 + 2.
  2. Press Enter.
  3. Look at the result under your input.
  4. Try another expression.

How to create a variable and use it step by step

  1. Type let followed by a name.
  2. Add = and a value.
  3. End with ;.
  4. Use the variable in an expression.

How to control precedence with parentheses step by step

  1. Write the expression without parentheses first.
  2. See what JavaScript calculates.
  3. Add parentheses to change the order.
  4. Compare the results.

How to check the type of a value step by step

  1. Type typeof followed by a value.
  2. Press Enter.
  3. See the type name in the console.

Real-life Examples

  • Banks: Use expressions to calculate interest.
  • Schools: Use expressions to average scores.
  • Homes: Use expressions to total shopping.
  • Startups: Use expressions to check stock levels.
  • Web apps: Use expressions to validate forms.

Nigerian Examples

  • Lagos traders: Calculate price * quantity for sales.
  • Abuja banks: Use balance + interest to update accounts.
  • Port Harcourt schools: Average math + english + science.
  • Onitsha shop owners: Subtract stock - sold to track goods.
  • Kano fintechs: Use amount - fee to send money.

Fun Examples Children Can Relate To

  • Pocket money: 20 - 5 for what is left.
  • Games: playerScore + 10 for a new score.
  • Snacks: price * 2 for two sweets.
  • Toys: toys - borrowed for how many remain.
  • Reading: booksRead + 1 for a new book.

Everyday Examples

  • Shopping: 2 * 500 for two loaves of bread.
  • Budget: income - expenses for savings.
  • Time: hours + minutes / 60 for total hours.
  • Cooking: cups * 2 to double a recipe.
  • Travel: speed * time for distance.

Parent Tips

  • Show your child how math appears in real life.
  • Encourage them to test expressions in the browser console.
  • Keep it fun — try simple examples together.
  • Praise them for trying new things.
  • Read about JavaScript with them.
  • Remind them that mistakes are okay.
  • Let them teach you what they learned.
  • Set short, simple practice sessions.
  • Use Nigerian examples they can relate to.
  • Support their learning journey.

Interesting Facts

  • The + operator also joins text together.
  • JavaScript uses floating-point math.
  • Parentheses have the highest precedence.
  • Every website uses hundreds of expressions.
  • typeof is an operator too!
  • Operators can be grouped by category.
  • JavaScript runs in every modern browser.
  • Nigerian students are learning JavaScript faster than ever.

Did You Know?

  • Did you know the console can remember your last expression?
  • Did you know parentheses can change the result of an expression?
  • Did you know "5" + 5 gives "55" in JavaScript?
  • Did you know you can use variables before you know their value?
  • Did you know "typeof null" returns "object"?
  • Did you know JavaScript has over 40 operators?
  • Did you know the same symbol can mean different things?
  • Did you know Nigeria has one of the fastest-growing developer communities in Africa?

Remember This

  • Operators are symbols that do actions.
  • Expressions give values.
  • Operands are values.
  • Types matter: number, string, boolean.
  • Statements are full instructions.
  • The console is your testing ground.
  • Variables hold values.
  • Precedence controls order.
  • Parentheses override precedence.
  • Best practices prevent bugs.

Common Mistakes

  • Forgetting parentheses.
  • Mixing numbers and strings.
  • Missing semicolons.
  • Using = instead of ===.
  • Wrong variable names.
  • Dividing by zero.
  • Confusing statements with expressions.
  • Not testing in the console first.

Best Practices

  • Use clear variable names.
  • Use parentheses to make meaning clear.
  • Use === instead of ==.
  • Keep expressions short.
  • Add spaces around operators.
  • Comment tricky expressions.
  • Test in the console first.
  • Check types with typeof.
  • Avoid nested expressions.
  • Read error messages carefully.

Illustrations and Diagrams

Expression Anatomy

  Operand   Operator   Operand
     5         +         3
                    |
                    V
                 Expression
                    |
                    V
                  Value: 8
  

Statement vs Expression

  Statement:   let total = 2 + 3;
                        \_____/
                        Expression
  

Operator Precedence

  Step 1: ( )
  Step 2: * /
  Step 3: + -
  Step 4: left to right
  

Variable Use

  let price = 3000;
  let qty   = 2;
  price * qty  →  6000
  

Your Learning Journey

  Module 1: Foundations
       |
       V
  Module 2: Arithmetic & Assignment
       |
       V
  Module 3: Comparison & Logic
       |
       V
  Module 4: Advanced & Certification
       |
       V
  Web Operators Expert 🎉
  

Comparison Tables

Statement vs Expression

FeatureStatementExpression
PurposeFull instructionProduces a value
Examplelet x = 5;2 + 3
Can stand alone?YesSometimes

Types of Values

TypeExample
Number42, 3.14
String"Ada", "Hello"
Booleantrue, false
Nullnull
Undefinedundefined

Precedence Order

OrderOperators
1( )
2* /
3+ -
4Left to right

Common Mistakes vs Fixes

MistakeFix
Missing ( )Add parentheses
Mixing typesUse the right type
Using = not ===Use === for compare
Missing ;Add semicolon

Lesson Summaries

Lesson 1: An operator is a symbol that does an action.

Lesson 2: An expression produces a value.

Lesson 3: Operands are the values in an expression.

Lesson 4: Values come in types: number, string, boolean, etc.

Lesson 5: Statements are full instructions; expressions are parts.

Lesson 6: Expressions make websites think and react.

Lesson 7: The browser console is your testing tool.

Lesson 8: Running an expression gives an instant value.

Lesson 9: Variables hold values in named containers.

Lesson 10: Variables can be used inside expressions.

Lesson 11: Operator precedence decides calculation order.

Lesson 12: Parentheses group parts of an expression.

Lesson 13: Common mistakes: missing parentheses, wrong types.

Lesson 14: Best practices: clear names, parentheses, simple expressions.

Lesson 15: You now understand the basics of operators and expressions.

End-of-Module Summary

Congratulations! You have finished Module One of the Operators & Expressions for Web course. You learned what an operator is and what an expression is. You learned about operands, values, and data types. You learned the difference between statements and expressions. You learned how to open the browser console and run expressions. You learned how to create variables and use them in expressions. You learned about operator precedence and parentheses. You learned common mistakes and best practices. Most importantly, you now understand the foundation of every line of JavaScript you will ever write. In the next module, you will learn about arithmetic and assignment operators in depth.

Frequently Asked Questions

  1. What is an operator? A symbol that does an action on values.
  2. What is an expression? A piece of code that produces a value.
  3. What is an operand? A value that an operator works on.
  4. What are data types? Number, string, boolean, null, undefined.
  5. What is the difference between a statement and an expression? A statement is a full instruction. An expression produces a value.
  6. How do I open the browser console? Press Ctrl + Shift + J (Windows) or Cmd + Option + J (Mac).
  7. What is a variable? A named container for a value.
  8. What is operator precedence? The order in which operators are calculated.
  9. Why use parentheses? To group parts of an expression and control the order.
  10. What are common mistakes? Missing parentheses, wrong types, missing semicolons.

Matching Exercises

Match the term to its meaning.

TermMeaning
1. OperatorA. A value an operator works on
2. ExpressionB. A symbol that does an action
3. OperandC. A named container for a value
4. VariableD. A piece of code that produces a value
5. StatementE. A full instruction in code

Answers: 1-B, 2-D, 3-A, 4-C, 5-E

Scenario-based Exercises

  1. Scenario: You want to add two numbers. Which operator?
    Answer: + (addition).
  2. Scenario: You want to group numbers before multiplying.
    Answer: Use parentheses ( ).
  3. Scenario: You want to store a value for later.
    Answer: Use a variable.
  4. Scenario: You want to check a value’s type.
    Answer: Use typeof.
  5. Scenario: You want to test an expression quickly.
    Answer: Use the browser console.

Group Activity

Title: “Build a Mini Calculator in the Console”

Instructions: In groups of 3–4, open the browser console and together type 5 different expressions. Include one with parentheses. Explain each result to the class. Try to use Nigerian examples like price × quantity.

Goal: Practice typing and reading expressions.

Individual Activity

Task: Open the browser console. Type and run at least 5 expressions:

  • One addition.
  • One multiplication.
  • One string concatenation.
  • One with parentheses.
  • One variable used in an expression.

Write down each expression and its answer.

Mini Project

Project: “My First JavaScript Expressions Notebook”

Create a document with at least 10 expressions:

  • Title and purpose of each expression.
  • The expression code.
  • Its value.
  • A short explanation.

Example:

  Purpose: Total price of 2 bags of rice
  Code: 2 * 3000
  Value: 6000
  Explanation: Multiply quantity by price.
  

Practical Assignment

Assignment: Interview a family member who sells goods. Ask them:

  1. How do they calculate prices?
  2. How do they add or subtract money?
  3. How do they decide if something is profitable?

Then write 5 JavaScript expressions that match their calculations.

Submit: Your 5 expressions with explanations.

Key Takeaways

  • Operators are symbols that do actions.
  • Expressions give values.
  • Operands are values.
  • Types matter.
  • Statements are full instructions.
  • The console is your testing ground.
  • Variables hold values.
  • Precedence controls order.
  • Parentheses override precedence.
  • Best practices prevent bugs.

Classroom Discussion Questions

  1. What is an operator, and what does it do?
  2. What is an expression, and how is it different from a statement?
  3. Why do we need operands?
  4. Why do data types matter in expressions?
  5. What is the browser console used for?
  6. How do variables help us write better code?
  7. Why does operator precedence matter?
  8. How can parentheses change the answer?
  9. What are three common mistakes in expressions?
  10. What did Ada learn from helping her mother’s shop?

Preparation for Module Two

In Module Two, we will dive deep into arithmetic and assignment operators. We will cover:

  • Addition, subtraction, multiplication, division.
  • Modulus (%) and exponent (**).
  • Increment (++) and decrement (--).
  • Assignment operators like +=, -=, *=, /=.
  • Operator precedence with arithmetic.
  • Common math mistakes.

To prepare, complete the practical assignment and review the key vocabulary. Practice a few expressions in the browser console. Bring your curiosity!

See you in Module Two!


End of Module One – Operators & Expressions for Web

3

Module Two

Operators & Expressions for Web – Module Two

Module Two: Arithmetic and Assignment Operators – Doing Math on the Web

“Operators & Expressions for Web” – Learn how JavaScript thinks and calculates

Module Introduction

Welcome back, young web coder! In Module One, you learned what operators and expressions are. You learned that operators are symbols that do actions, and expressions are pieces of code that produce values. You also learned how to use the browser console and how variables hold values.

Now it is time to roll up our sleeves and do math. In Module Two, we will learn about arithmetic operators (like +, -, *, /) and assignment operators (like =, +=, -=). These are the tools every website uses to count things, calculate prices, track scores, and more.

Think of arithmetic operators as your math tools. Assignment operators are like labels on boxes that store results. Together, they make websites smart. Let’s begin!

Learning Objectives

After finishing this module, you will be able to:

  • Explain what arithmetic operators do.
  • Use +, -, *, / in expressions.
  • Use modulus (%) and exponent (**).
  • Use increment (++) and decrement (--).
  • Explain what assignment operators do.
  • Use =, +=, -=, *=, /=, and %=.
  • Understand operator precedence in arithmetic.
  • Use parentheses to control calculations.
  • Give Nigerian examples of arithmetic in business.
  • Complete a mini project and practical assignment.

Warm-up Story: Ngozi’s Restaurant Bill

Ngozi is 14 years old and lives in Enugu. Her aunt runs a small restaurant. Every day, customers order plates of food, bottles of water, and soft drinks. Ngozi’s aunt wrote the prices on paper and added them by hand. Sometimes she made mistakes.

One day, Ngozi said, "Auntie, let me build you a simple bill calculator." She opened her browser console and typed:

let plate  = 2500;
let water  = 200;
let drink  = 500;

let total = (2 * plate) + (3 * water) + (1 * drink);
  

The console showed: 5600. Her aunt was amazed. Ngozi explained:

  • * multiplied the quantity by the price.
  • + added the subtotals.
  • ( ) grouped each item before adding.
  • = stored the answer in total.

Next, Ngozi added a discount:

let discount = 500;
total -= discount; // total is now 5100
  

Her aunt was very happy. "This will save me so much time!" she said.

Ngozi smiled. "And I can even add more features later — like tax, tips, or percentages."

Moral of the story: Arithmetic and assignment operators are powerful tools for real businesses. They can calculate prices, discounts, and totals quickly and accurately.

Main Lessons

Lesson 1: What are Arithmetic Operators?

Definition: Arithmetic operators are symbols that perform math operations on numbers.

Why it is important: They are the foundation of every calculation on the web.

Simple explanation: They are like the buttons on a calculator.

Real-life example: A bank adds interest with +.

School example: A teacher averages scores using + and /.

Home example: A family subtracts expenses using -.

Nigerian example: A trader multiplies price by quantity using *.

Illustration:

  Arithmetic Operators:

  +   addition
  -   subtraction
  *   multiplication
  /   division
  %   modulus (remainder)
  **  exponent (power)
  

Mini summary: Arithmetic operators do math on numbers.

Lesson 2: Addition (+)

Definition: The + operator adds two or more numbers together.

Why it is important: It is the most common operator in any program.

Simple explanation: + puts values together.

Real-life example: A bank adds deposits.

School example: A student adds scores.

Home example: A family adds grocery prices.

Nigerian example: A trader adds totals from two shops.

Illustration:

  5 + 3     →  8
  10 + 20   →  30
  2.5 + 1.5 →  4
  

Mini summary: + adds numbers together.

Lesson 3: Subtraction (-)

Definition: The - operator subtracts one number from another.

Why it is important: It is used for balances, discounts, and differences.

Simple explanation: - takes away one value from another.

Real-life example: A bank subtracts withdrawals.

School example: A student finds how many points they lost.

Home example: A family subtracts savings from income.

Nigerian example: A trader subtracts expenses from sales.

Illustration:

  10 - 4   →  6
  50 - 25  →  25
  5 - 8    →  -3
  

Mini summary: - subtracts one number from another.

Lesson 4: Multiplication (*)

Definition: The * operator multiplies numbers together.

Why it is important: It is used to calculate totals with quantity and price.

Simple explanation: * repeats a number many times, quickly.

Real-life example: A bank calculates interest using multiplication.

School example: A student multiplies score by weight.

Home example: A family multiplies price by quantity.

Nigerian example: A trader multiplies quantity by unit price.

Illustration:

  3 * 4    →  12
  7 * 2    →  14
  2.5 * 4  →  10
  

Mini summary: * multiplies numbers together.

Lesson 5: Division (/)

Definition: The / operator divides one number by another.

Why it is important: It is used for averages, shares, and rates.

Simple explanation: / splits a number into equal parts.

Real-life example: A bank divides profit among shareholders.

School example: A student averages scores by dividing by number of subjects.

Home example: A family splits a bill among members.

Nigerian example: A trader divides the cost of a bag of rice to find the price per cup.

Illustration:

  12 / 3   →  4
  100 / 4  →  25
  7 / 2    →  3.5
  

Mini summary: / divides one number by another.

Lesson 6: Modulus (%)

Definition: The % operator gives the remainder after division.

Why it is important: It is used to check even/odd numbers and repeating cycles.

Simple explanation: % shows what is left over after dividing.

Real-life example: A bank checks if a number of transactions is even.

School example: A teacher divides students into groups of 4 and checks who is left over.

Home example: A family shares items equally and sees what is left.

Nigerian example: A trader packs eggs in cartons of 12 and checks the remainder.

Illustration:

  10 % 3   →  1  (because 10 ÷ 3 = 3 remainder 1)
  8 % 2    →  0  (even number)
  7 % 2    →  1  (odd number)
  

Mini summary: % gives the remainder after division.

Lesson 7: Exponent (**)

Definition: The ** operator raises a number to a power.

Why it is important: It is used for squaring, area, and growth calculations.

Simple explanation: ** multiplies a number by itself many times.

Real-life example: A bank calculates compound interest.

School example: A student calculates the area of a square.

Home example: A family calculates the area of a room.

Nigerian example: A trader calculates the area of farmland.

Illustration:

  2 ** 3   →  8   (2 × 2 × 2)
  5 ** 2   →  25  (5 × 5)
  10 ** 0  →  1
  

Mini summary: ** raises a number to a power.

Lesson 8: Increment (++) and Decrement (--)

Definition: ++ adds 1 to a number. -- subtracts 1 from a number.

Why it is important: They are used in counters and loops.

Simple explanation: ++ is like saying "one more". -- is like saying "one less".

Real-life example: A bank counts transactions one by one.

School example: A teacher counts students entering the class.

Home example: A family counts how many eggs are used.

Nigerian example: A trader counts how many customers entered today.

Illustration:

  let count = 0;
  count++;   // count is now 1
  count++;   // count is now 2
  count--;   // count is now 1
  

Mini summary: ++ adds 1 and -- subtracts 1 from a number.

Lesson 9: What are Assignment Operators?

Definition: Assignment operators store values into variables.

Why it is important: Without them, you cannot save or reuse results.

Simple explanation: Assignment operators are like labeled boxes where you put values.

Real-life example: A bank assigns a value to "balance".

School example: A teacher assigns a value to "score".

Home example: A family assigns a value to "monthlyBudget".

Nigerian example: A trader assigns a value to "totalSales".

Illustration:

  let balance = 5000;   // assign
  balance = 6000;       // reassign
  

Mini summary: Assignment operators store values into variables.

Lesson 10: The Simple Assignment (=)

Definition: The = operator stores the value on the right into the variable on the left.

Why it is important: It is the most common assignment operator.

Simple explanation: = means "put this value into this box".

Real-life example: A bank sets balance to 5000.

School example: A student sets score to 90.

Home example: A family sets rent to 150000.

Nigerian example: A trader sets price to 3000.

Illustration:

  let x = 5;
  let name = "Ada";
  let isOpen = true;
  

Mini summary: = stores a value into a variable.

Lesson 11: Compound Assignment (+=, -=, *=, /=)

Definition: Compound assignment operators combine math and assignment in one step.

Why it is important: They save time and make code cleaner.

Simple explanation: Instead of writing x = x + 5, you write x += 5.

Real-life example: A bank adds interest to a balance with +=.

School example: A student adds bonus points with +=.

Home example: A family adds an expense with +=.

Nigerian example: A trader adds today’s sales with +=.

Illustration:

  let x = 10;
  x += 5;   // same as x = x + 5   → 15
  x -= 3;   // same as x = x - 3   → 12
  x *= 2;   // same as x = x * 2   → 24
  x /= 4;   // same as x = x / 4   → 6
  

Mini summary: Compound assignment combines math with assignment.

Lesson 12: Modulus Assignment (%=)

Definition: The %= operator assigns the remainder to a variable.

Why it is important: It is useful for cycles and remainders.

Simple explanation: It is like saying "put the remainder back into the box".

Real-life example: A bank uses %= to rotate transaction IDs.

School example: A teacher uses %= to pack students into groups.

Home example: A family uses %= to split bills evenly.

Nigerian example: A trader uses %= to know how many items will remain after packing.

Illustration:

  let x = 17;
  x %= 5;   // same as x = 17 % 5   → 2
  

Mini summary: %= assigns the remainder to a variable.

Lesson 13: Operator Precedence in Arithmetic

Definition: Precedence decides which operator runs first in an expression.

Why it is important: Wrong precedence gives wrong answers.

Simple explanation: JavaScript follows math rules: multiply before adding.

Real-life example: A bank multiplies interest before adding to balance.

School example: A student multiplies scores before averaging.

Home example: A family multiplies items before summing the bill.

Nigerian example: A trader multiplies quantity by price before adding other items.

Illustration:

  2 + 3 * 4   →  14   (* first)
  (2 + 3) * 4 →  20   (parentheses first)
  2 + 3 - 1   →  4    (left to right)
  

Step-by-step:

  1. Parentheses ( ).
  2. Exponents **.
  3. Multiplication *, Division /, Modulus %.
  4. Addition +, Subtraction -.
  5. Left to right when equal.

Mini summary: Precedence decides the order of calculation. Parentheses go first.

Lesson 14: Common Mistakes in Arithmetic

Definition: Mistakes happen. Knowing them helps you avoid them.

Why it is important: Small mistakes cause big errors.

Simple explanation: Like misreading a price at the market.

Real-life example: A bank charges wrong interest due to a wrong operator.

School example: A teacher misaverages due to missing parentheses.

Home example: A family miscounts a bill.

Nigerian example: A trader undercharges a customer.

Table of common mistakes:

MistakeWhat HappensHow to Fix
Forgetting parenthesesWrong answerAdd ( )
Using = instead of ==Assignment instead of checkUse === to compare
Dividing by zeroInfinityCheck denominator
Mixing numbers and stringsWrong resultConvert types
Missing semicolonErrorAdd ;
Wrong variable nameReferenceErrorCheck spelling

Mini summary: Common mistakes: missing parentheses, wrong types, missing semicolons.

Lesson 15: Best Practices for Arithmetic and Assignment

Definition: Best practices are good habits that make math code clean and safe.

Why it is important: Good habits prevent bugs and help others read your code.

Simple explanation: Like keeping your calculator clean.

Real-life example: A bank writes clean math code in its apps.

School example: A student writes neat calculations.

Home example: A family keeps a tidy budget sheet.

Nigerian example: A business writes simple, readable code.

List of best practices:

  • Use parentheses to be clear.
  • Use += instead of repeating x = x + .
  • Use Math.round() for money.
  • Check for division by zero.
  • Name variables clearly.
  • Test expressions in the console.
  • Add comments for tricky math.
  • Use consistent spacing around operators.
  • Avoid very long expressions.
  • Read error messages carefully.

Mini summary: Best practices: parentheses, clean names, and testing.

Lesson 16: Putting It All Together – Your Arithmetic Toolkit

You now know how to do math in JavaScript.

What you learned:

  • Arithmetic operators
  • Addition, subtraction, multiplication, division
  • Modulus and exponent
  • Increment and decrement
  • Assignment and compound assignment
  • Precedence and parentheses
  • Common mistakes and best practices

Next steps: In Module Three, you will learn about comparison, logical, and string operators.

Illustration:

  Your Learning Journey:

  Module 1: Foundations
       |
       V
  Module 2: Arithmetic & Assignment
       |
       V
  Module 3: Comparison & Logic
       |
       V
  Module 4: Advanced & Certification
       |
       V
  Web Operators Expert 🎉
  

Mini summary: You now have a full arithmetic toolkit. Time to compare and combine values!

Key Vocabulary

WordSimple Definition
ArithmeticMath with numbers.
AdditionCombining numbers with +.
SubtractionTaking away with -.
MultiplicationRepeated addition with *.
DivisionSplitting into equal parts with /.
ModulusThe remainder after division (%).
ExponentNumber raised to a power (**).
IncrementAdd 1 to a number (++).
DecrementSubtract 1 from a number (--).
AssignmentStoring a value in a variable (=).
Compound AssignmentMath plus assignment (+=, -=, etc.).
PrecedenceOrder of calculation.
Parentheses( ) group calculations.
RemainderWhat is left after division.
InfinityA result when dividing by zero.

Important Concepts

  • Arithmetic operators do math: +, -, *, /, %, **.
  • Modulus gives remainder: Very useful for cycles.
  • Exponent raises to a power: Useful for area and growth.
  • ++ and -- count up or down: Great for counters.
  • = stores values: Foundation of variables.
  • Compound assignments save time: x += 5 instead of x = x + 5.
  • Precedence controls order: Multiply before adding.
  • Parentheses override precedence: Use them freely.
  • Test with the console: Fast and safe.
  • Watch for division by zero: Gives Infinity.

Step-by-step Explanations

How to do simple arithmetic in the console step by step

  1. Open the console.
  2. Type 2 + 3 and press Enter.
  3. See 5.
  4. Try 10 * 5 and press Enter.
  5. See 50.

How to use += step by step

  1. Create a variable with let x = 10;.
  2. Type x += 5;.
  3. Check the value with x.
  4. See 15.

How to use modulus step by step

  1. Type 10 % 3.
  2. Press Enter.
  3. See 1.
  4. Try 8 % 2 to get 0.

How to use parentheses step by step

  1. Type 2 + 3 * 4 and see 14.
  2. Type (2 + 3) * 4 and see 20.
  3. Notice how parentheses change the answer.

How to use increment step by step

  1. Type let count = 0;.
  2. Type count++;.
  3. Check count and see 1.
  4. Try again to get 2.

Real-life Examples

  • Banks: Calculate interest with * and add it with +.
  • Restaurants: Multiply item price by quantity.
  • Shops: Subtract stock sold from stock available.
  • Schools: Average scores with / and +.
  • Web apps: Track how many items are in a cart.

Nigerian Examples

  • Lagos traders: price * quantity for invoices.
  • Abuja banks: balance += interest to update accounts.
  • Port Harcourt schools: (a + b + c) / 3 for averages.
  • Onitsha shop owners: stock -= sold for remaining goods.
  • Kano fintechs: amount %= 100 for split payments.

Fun Examples Children Can Relate To

  • Pocket money: 20 - 5 for what is left.
  • Games: score += 10 for a new high score.
  • Snacks: price * 2 for two sweets.
  • Toys: toys -= 1 for each toy given away.
  • Reading: pagesRead += 10 every day.

Everyday Examples

  • Shopping: 2 * 500 for two loaves of bread.
  • Budget: income -= expenses for savings.
  • Time: hours + minutes / 60 for total hours.
  • Cooking: cups *= 2 to double a recipe.
  • Travel: speed * time for distance.

Parent Tips

  • Show your child how math appears in real life.
  • Encourage them to test expressions in the browser console.
  • Keep it fun — try simple examples together.
  • Praise them for trying new things.
  • Read about JavaScript with them.
  • Remind them that mistakes are okay.
  • Let them teach you what they learned.
  • Set short, simple practice sessions.
  • Use Nigerian examples they can relate to.
  • Support their learning journey.

Interesting Facts

  • JavaScript uses floating-point math (like decimals).
  • 0.1 + 0.2 does not always equal 0.3 in JavaScript.
  • Division by zero gives Infinity.
  • Modulus (%) is used to test even numbers.
  • Compound assignments make code shorter.
  • Increment (++) is common in loops.
  • Parentheses override everything else.
  • Nigerian businesses use math in every transaction.

Did You Know?

  • Did you know "5" + 5 gives "55" (not 10)?
  • Did you know Math.round() rounds decimals?
  • Did you know 2 ** 10 is 1024?
  • Did you know ++ before and after a variable act differently?
  • Did you know you can chain assignments like a = b = 5?
  • Did you know -0 exists in JavaScript?
  • Did you know Infinity is a valid number?
  • Did you know 10 % 2 is always 0 for even numbers?

Remember This

  • + adds, - subtracts.
  • * multiplies, / divides.
  • % gives the remainder.
  • ** raises to a power.
  • ++ adds 1, -- subtracts 1.
  • = stores a value.
  • +=, -=, *=, /= are shortcuts.
  • Multiplication before addition.
  • Parentheses change the order.
  • Test in the console first.

Common Mistakes

  • Forgetting parentheses.
  • Using = instead of ==.
  • Dividing by zero.
  • Mixing numbers and strings.
  • Missing semicolons.
  • Wrong variable names.
  • Confusing ++ before vs after.
  • Not testing code first.

Best Practices

  • Use parentheses to be clear.
  • Use += instead of repeating x = x + .
  • Use Math.round() for money.
  • Check for division by zero.
  • Name variables clearly.
  • Test expressions in the console.
  • Add comments for tricky math.
  • Use consistent spacing around operators.
  • Avoid very long expressions.
  • Read error messages carefully.

Illustrations and Diagrams

Arithmetic Operators

  +   add
  -   subtract
  *   multiply
  /   divide
  %   remainder
  **  power
  

Compound Assignment

  x = x + 5   →   x += 5
  x = x - 3   →   x -= 3
  x = x * 2   →   x *= 2
  x = x / 4   →   x /= 4
  

Precedence Order

  1. ( )
  2. **
  3. * / %
  4. + -
  

Remainder Example

  10 % 3

  10 ÷ 3 = 3 remainder 1

  So 10 % 3 = 1
  

Your Learning Journey

  Module 1: Foundations
       |
       V
  Module 2: Arithmetic & Assignment
       |
       V
  Module 3: Comparison & Logic
       |
       V
  Module 4: Advanced & Certification
       |
       V
  Web Operators Expert 🎉
  

Comparison Tables

Basic Arithmetic Operators

OperatorMeaningExample
+Add5 + 3 = 8
-Subtract5 - 3 = 2
*Multiply5 * 3 = 15
/Divide10 / 2 = 5
%Remainder10 % 3 = 1
**Power2 ** 3 = 8

Assignment Operators

OperatorMeaningExample
=Assignx = 5
+=Add and assignx += 5
-=Subtract and assignx -= 5
*=Multiply and assignx *= 5
/=Divide and assignx /= 5
%=Remainder and assignx %= 5

++ Before vs After

FormMeaning
x++Use x, then add 1
++xAdd 1, then use x

Common Math Outputs

ExpressionValue
5 + 38
5 / 22.5
5 % 21
5 / 0Infinity
0 / 0NaN

Lesson Summaries

Lesson 1: Arithmetic operators do math on numbers.

Lesson 2: + adds numbers.

Lesson 3: - subtracts numbers.

Lesson 4: * multiplies numbers.

Lesson 5: / divides numbers.

Lesson 6: % gives the remainder.

Lesson 7: ** raises to a power.

Lesson 8: ++ adds 1, -- subtracts 1.

Lesson 9: Assignment operators store values.

Lesson 10: = stores a value into a variable.

Lesson 11: Compound assignments combine math with assignment.

Lesson 12: %= assigns the remainder.

Lesson 13: Precedence controls calculation order.

Lesson 14: Common mistakes: missing parentheses, wrong types.

Lesson 15: Best practices: parentheses, clean names, testing.

Lesson 16: You now have a full arithmetic toolkit.

End-of-Module Summary

Congratulations! You have finished Module Two of the Operators & Expressions for Web course. You learned arithmetic operators (+, -, *, /, %, **) and assignment operators (=, +=, -=, *=, /=, %=). You learned about increment and decrement. You learned about precedence and parentheses. You learned common mistakes and best practices. Most importantly, you can now do math in JavaScript, which is the foundation of every website and app. In the next module, you will learn about comparison, logical, and string operators.

Frequently Asked Questions

  1. What is the + operator? It adds numbers.
  2. What is the - operator? It subtracts numbers.
  3. What is the * operator? It multiplies numbers.
  4. What is the / operator? It divides numbers.
  5. What is the % operator? It gives the remainder after division.
  6. What is the ** operator? It raises a number to a power.
  7. What does ++ do? Adds 1 to a number.
  8. What does -- do? Subtracts 1 from a number.
  9. What does += do? Adds a value and stores the result.
  10. What is operator precedence? The order in which operators are calculated.

Matching Exercises

Match the operator to its meaning.

OperatorMeaning
1. +A. Multiply
2. -B. Add
3. *C. Remainder
4. %D. Subtract
5. **E. Power

Answers: 1-B, 2-D, 3-A, 4-C, 5-E

Scenario-based Exercises

  1. Scenario: You want to add two numbers.
    Answer: Use +.
  2. Scenario: You want to calculate change after shopping.
    Answer: Use -.
  3. Scenario: You want to find the total of 5 items at ₦300 each.
    Answer: Use *.
  4. Scenario: You want to split a bill among 3 people.
    Answer: Use /.
  5. Scenario: You want to check if a number is even.
    Answer: Use % 2.

Group Activity

Title: “Build a Simple Bill Calculator Together”

Instructions: In groups of 3–4, choose 3 items with prices and quantities. Write JavaScript expressions that calculate the total. Use at least one * and one +. Add a discount with -=. Print the results in the console. Present your code to the class.

Goal: Practice arithmetic and assignment operators.

Individual Activity

Task: Open the browser console. Type at least 6 expressions:

  • One addition.
  • One subtraction.
  • One multiplication.
  • One division.
  • One modulus.
  • One compound assignment.

Write down each expression and its result.

Mini Project

Project: “My First Bill Calculator”

Create a simple bill calculator in the console:

  • Choose 3 items with prices.
  • Ask for quantities (you can use fixed numbers).
  • Calculate subtotals with *.
  • Calculate total with +.
  • Apply a discount with -=.
  • Show the final total with console.log().

Example:

  let price1 = 2500, qty1 = 2;
  let price2 = 200,  qty2 = 3;
  let price3 = 500,  qty3 = 1;

  let total = (price1 * qty1) + (price2 * qty2) + (price3 * qty3);
  total -= 500;  // discount
  console.log(total);  // 5100
  

Practical Assignment

Assignment: Ask a family member who sells goods how they price items. Then write JavaScript code that:

  1. Stores price and quantity.
  2. Multiplies them together.
  3. Adds multiple items.
  4. Applies a discount.
  5. Shows the final total with console.log().

Submit: Your code and a short explanation.

Key Takeaways

  • + adds, - subtracts.
  • * multiplies, / divides.
  • % gives the remainder.
  • ** raises to a power.
  • ++ adds 1, -- subtracts 1.
  • = stores a value.
  • +=, -=, *=, /= are shortcuts.
  • Multiplication before addition.
  • Parentheses change the order.
  • Test in the console first.

Classroom Discussion Questions

  1. What is the difference between + and *?
  2. Why is modulus (%) useful?
  3. What is the difference between ++ and +=?
  4. Why is operator precedence important?
  5. How can parentheses change the answer?
  6. What happens when you divide by zero?
  7. Why should you use === instead of ==?
  8. What mistakes do beginners make with math in JavaScript?
  9. How do real businesses use arithmetic operators?
  10. What did Ngozi build for her aunt’s restaurant?

Preparation for Module Three

In Module Three, we will learn about comparison, logical, and string operators. We will cover:

  • Equal (==) vs strict equal (===).
  • Not equal (!=) and (!==).
  • Greater than, less than, and equal variants.
  • Logical AND (&&), OR (||), NOT (!).
  • String concatenation and template literals.
  • Truthy and falsy values.

To prepare, complete the practical assignment and review the key vocabulary. Practice a few expressions in the browser console. Bring your curiosity!

See you in Module Three!


End of Module Two – Operators & Expressions for Web

4

Module Three

Operators & Expressions for Web – Module Three

Module Three: Comparison, Logical and String Operators – Making Decisions on the Web

“Operators & Expressions for Web” – Learn how JavaScript thinks and calculates

Module Introduction

Welcome back, young web coder! In Module One, you learned the basics of operators and expressions. In Module Two, you learned arithmetic and assignment operators.

Now it is time to make JavaScript think. In this module, we will learn about comparison operators (like == and >), logical operators (like && and ||), and string operators (like + for joining text).

These operators are what make a website smart. They help a login page check if a password is correct. They help a shop page show "In Stock" only when items are available. They help a game decide if the player has won.

By the end of this module, you will be able to write JavaScript that compares, decides, and reacts — just like real web apps do.

Let’s begin!

Learning Objectives

After finishing this module, you will be able to:

  • Explain what comparison operators do.
  • Use ==, ===, !=, !==, >, <, >=, <=.
  • Understand the difference between == and ===.
  • Explain what logical operators do.
  • Use &&, ||, and ! in expressions.
  • Understand truthy and falsy values.
  • Join strings with the + operator.
  • Use template literals for cleaner strings.
  • Give Nigerian examples of comparisons and logic.
  • Complete a mini project and practical assignment.

Warm-up Story: Chidi’s Login Page

Chidi is 14 years old and lives in Port Harcourt. He built a simple login page for his school’s coding club. The page asked for a username and password.

At first, Chidi had a problem. His code accepted every password. Anyone could log in! He said, "I need my page to compare what the user typed to the real password."

His teacher said, "Use the strict equality operator ===."

Chidi wrote:

let entered = "coding4life";
let real    = "coding4life";

if (entered === real) {
  console.log("Welcome!");
} else {
  console.log("Wrong password");
}
  

The console printed: Welcome!. Chidi was very happy.

Next, he wanted the page to welcome "Admin" or "Member" based on the username. He used the logical OR operator:

let username = "ada";
if (username === "ada" || username === "admin") {
  console.log("Hello, leader!");
}
  

Finally, he wanted to show a greeting. He used string concatenation:

let greeting = "Hello, " + username + "!";
console.log(greeting);
  

His login page became smarter. It could compare, decide, and respond. Chidi learned that comparison and logical operators are the brains of any website.

Moral of the story: Comparison operators check. Logical operators combine checks. String operators join words. Together, they make websites smart.

Main Lessons

Lesson 1: What are Comparison Operators?

Definition: Comparison operators compare two values and return true or false.

Why it is important: They let websites make decisions.

Simple explanation: They answer questions like "Is this bigger?" or "Are these the same?"

Real-life example: A bank checks if a balance is above zero.

School example: A teacher checks if a score is above pass mark.

Home example: A family checks if the shopping total is within budget.

Nigerian example: A trader checks if stock is below reorder level.

Illustration:

  Comparison operators return:

  true   or   false
  

Mini summary: Comparison operators check values and give true or false.

Lesson 2: The Equality Operator (==)

Definition: The == operator checks if two values are equal after converting them to the same type.

Why it is important: It is an easy way to compare values quickly.

Simple explanation: == asks "Are these the same?" but it is very forgiving.

Real-life example: A bank checks if a typed PIN equals a stored PIN.

School example: A teacher checks if a score equals 100.

Home example: A family checks if two shopping lists match.

Nigerian example: A trader checks if two prices are the same.

Illustration:

  5 == 5       →  true
  "5" == 5     →  true   (type conversion!)
  true == 1    →  true
  

Mini summary: == checks equality but converts types first.

Lesson 3: Strict Equality (===)

Definition: The === operator checks if two values are equal AND have the same type.

Why it is important: It is safer and prevents surprises.

Simple explanation: === asks "Are these the same value and the same type?"

Real-life example: A bank checks if a typed PIN (a number) strictly equals the stored PIN.

School example: A teacher checks if a score (a number) strictly equals a target score.

Home example: A family checks if the quantity (a number) strictly equals 5.

Nigerian example: A trader checks if the price (a number) strictly equals ₦3000.

Illustration:

  5 === 5      →  true
  "5" === 5    →  false
  5 === "5"    →  false
  

Mini summary: === checks equality and type. Always prefer ===.

Lesson 4: Not Equal (!= and !==)

Definition: != checks if two values are not equal. !== checks if they are not equal OR not the same type.

Why it is important: Used to reject wrong values.

Simple explanation: They are the "opposite" of equality checks.

Real-life example: A bank rejects a wrong PIN.

School example: A teacher rejects a wrong answer.

Home example: A family rejects a wrong shopping item.

Nigerian example: A trader rejects a wrong price.

Illustration:

  5 != 3       →  true
  5 != 5       →  false
  "5" !== 5    →  true
  

Mini summary: != and !== check if values are different. !== is stricter.

Lesson 5: Greater Than and Less Than (>, <)

Definition: > checks if the left value is greater. < checks if it is less.

Why it is important: Used to compare numbers.

Simple explanation: They are the "bigger" and "smaller" checks.

Real-life example: A bank checks if a withdrawal is greater than the balance.

School example: A teacher checks if a score is greater than 50.

Home example: A family checks if the bill is less than the budget.

Nigerian example: A trader checks if stock is less than 10.

Illustration:

  10 > 5    →  true
  10 < 5    →  false
  7 > 7     →  false
  

Mini summary: > and < check bigger and smaller.

Lesson 6: Greater/Less Than or Equal (>=, <=)

Definition: >= checks if the left value is greater OR equal. <= checks if it is less OR equal.

Why it is important: Very common in form validation and grading.

Simple explanation: Same as > and <, but includes "equal to".

Real-life example: A bank allows withdrawals up to the balance (<=).

School example: A teacher passes anyone with score >= 50.

Home example: A family keeps spending <= income.

Nigerian example: A trader sells if quantity <= stock.

Illustration:

  10 >= 10   →  true
  10 >= 9    →  true
  5 <= 5     →  true
  5 <= 3     →  false
  

Mini summary: >= and <= include the equal case.

Lesson 7: What are Logical Operators?

Definition: Logical operators combine multiple true/false checks into one.

Why it is important: Real life has more than one condition.

Simple explanation: They are the "and", "or", and "not" of code.

Real-life example: A bank requires you to have an account AND a valid ID.

School example: You can attend the trip if you paid AND brought a permission slip.

Home example: You can go out if you finished chores AND did homework.

Nigerian example: You can buy stock if you have money AND the price is good.

Illustration:

  &&   AND  (both true)
  ||   OR   (at least one true)
  !    NOT  (flips true to false)
  

Mini summary: Logical operators combine conditions.

Lesson 8: Logical AND (&&)

Definition: && returns true only if both sides are true.

Why it is important: It enforces strict conditions.

Simple explanation: && is like saying "you must do both".

Real-life example: A bank checks if you have enough money AND a valid account.

School example: A teacher passes you only if you attended AND submitted all work.

Home example: You can watch TV if you cleaned AND did homework.

Nigerian example: A trader accepts an order if stock is available AND payment is confirmed.

Illustration:

  true  && true   →  true
  true  && false  →  false
  false && true   →  false
  false && false  →  false
  

Mini summary: && needs both sides to be true.

Lesson 9: Logical OR (||)

Definition: || returns true if at least one side is true.

Why it is important: It gives flexibility.

Simple explanation: || is like saying "either this or that is fine".

Real-life example: A bank accepts a phone number OR an email for contact.

School example: You can submit by email OR by hand.

Home example: You can shop at Market A OR Market B.

Nigerian example: A trader accepts payment by transfer OR cash.

Illustration:

  true  || true   →  true
  true  || false  →  true
  false || true   →  true
  false || false  →  false
  

Mini summary: || is true if at least one side is true.

Lesson 10: Logical NOT (!)

Definition: ! flips a true to false or a false to true.

Why it is important: Used to invert checks.

Simple explanation: ! is like saying "the opposite".

Real-life example: A bank shows "Not available" if a service is !available.

School example: A teacher marks a student absent if !present.

Home example: A family stays home if !sunny.

Nigerian example: A trader does not sell if !inStock.

Illustration:

  !true    →  false
  !false   →  true
  

Mini summary: ! flips true and false.

Lesson 11: Truthy and Falsy Values

Definition: Truthy values act like true in logical checks. Falsy values act like false.

Why it is important: They affect how && , ||, and if statements behave.

Simple explanation: Some values "feel" like true or false to JavaScript.

Real-life example: A bank treats an empty balance (0) as a "no" for a loan.

School example: An empty string ("") is treated as no answer.

Home example: An empty shopping list is treated as "nothing to buy".

Nigerian example: A trader treats null prices as "no price".

Illustration:

  Falsy values:
  false, 0, "", null, undefined, NaN

  Truthy values:
  "text", 1, -1, [], {}
  

Mini summary: Some values act like false, others act like true. Learn the list.

Lesson 12: String Operators – Joining Text

Definition: The + operator also joins strings together.

Why it is important: Websites show messages like "Welcome, Ada".

Simple explanation: + glues words together.

Real-life example: A bank says "Dear " + customer + "."

School example: A teacher greets students: "Hello, " + name.

Home example: A family writes "Happy birthday, " + name.

Nigerian example: A trader sends "Your order of " + qty + " items is ready."

Illustration:

  "Hello, " + "Ada"     →  "Hello, Ada"
  "Total: " + 5000      →  "Total: 5000"
  

Mini summary: The + operator joins strings.

Lesson 13: Template Literals (Backticks)

Definition: Template literals use backticks (`) to make joining strings easier.

Why it is important: They are cleaner than using + many times.

Simple explanation: They let you put values inside a sentence directly.

Real-life example: A bank writes: `Dear ${name}, your balance is ${balance}`.

School example: A teacher writes: `${name} scored ${score}`.

Home example: A family writes: `We have ${count} eggs left.`

Nigerian example: A trader writes: `Your order costs ₦${price}.`

Illustration:

  let name = "Ada";
  let score = 90;

  `Hello, ${name}! Your score is ${score}.`
  

Mini summary: Template literals use backticks and ${ } for clean strings.

Lesson 14: Common Mistakes with Comparisons and Logic

Definition: Mistakes happen. Knowing them helps you avoid them.

Why it is important: Wrong comparisons give wrong decisions.

Simple explanation: Like using the wrong key on a lock.

Real-life example: A bank using == instead of === can accept "5" as 5.

School example: A teacher using = instead of === gives the wrong grade.

Home example: A family using || instead of && accepts the wrong list.

Nigerian example: A trader using < instead of <= misses a sale.

Table of common mistakes:

MistakeWhat HappensHow to Fix
Using == instead of ===Wrong type acceptedUse ===
Using = instead of ===Assigns valueUse === in conditions
Confusing && and ||Wrong logicRead conditions aloud
Not checking truthy/falsyWrong branchTest with console
Forgetting backticksString errorUse ` ` for template literals
Missing $ before { }Wrong outputWrite ${value}

Mini summary: Common mistakes: == vs ===, && vs ||, and forgotten backticks.

Lesson 15: Best Practices for Comparison and Logic

Definition: Best practices are good habits that make logic clear and safe.

Why it is important: Good habits prevent bugs and confusion.

Simple explanation: Like a clean desk — easier to think.

Real-life example: A bank writes clean conditions.

School example: A student writes clear if-statements.

Home example: A family writes clear shopping rules.

Nigerian example: A business writes clear code.

List of best practices:

  • Use === and !== instead of == and !=.
  • Name variables clearly.
  • Use parentheses to make logic clear.
  • Test in the console.
  • Use template literals for strings.
  • Avoid deep nesting of conditions.
  • Read your conditions aloud.
  • Use comments for tricky logic.
  • Check for truthy/falsy carefully.
  • Keep lines short.

Mini summary: Best practices: use ===, clear names, and test often.

Lesson 16: Putting It All Together – Your Logic Toolkit

You now know how to compare and combine values.

What you learned:

  • Comparison operators
  • == vs ===
  • != and !==
  • >, <, >=, <=
  • Logical operators &&, ||, !
  • Truthy and falsy values
  • String + operator
  • Template literals
  • Common mistakes and best practices

Next steps: In Module Four, you will learn advanced operators and complete your certification project.

Illustration:

  Your Learning Journey:

  Module 1: Foundations
       |
       V
  Module 2: Arithmetic & Assignment
       |
       V
  Module 3: Comparison & Logic
       |
       V
  Module 4: Advanced & Certification
       |
       V
  Web Operators Expert 🎉
  

Mini summary: You now have a full logic toolkit. Time to learn advanced operators!

Key Vocabulary

WordSimple Definition
Comparison OperatorChecks two values and returns true/false.
Equality (==)Checks equal after type conversion.
Strict Equality (===)Checks equal value and type.
Not Equal (!=)Checks if values are different.
Strict Not Equal (!==)Checks if values or types differ.
Greater Than (>)Checks if left is bigger.
Less Than (<)Checks if left is smaller.
Greater Than or Equal (>=)Bigger or same.
Less Than or Equal (<=)Smaller or same.
Logical AND (&&)Both must be true.
Logical OR (||)At least one must be true.
Logical NOT (!)Flips true and false.
TruthyValues that act like true.
FalsyValues that act like false.
Template LiteralString using backticks and ${ }.

Important Concepts

  • Comparisons return true or false: They power decisions.
  • === is safer than ==: It checks type too.
  • !== is the opposite of ===: Strict not equal.
  • > and < compare size: >= and <= include equal.
  • && needs both: Strict condition.
  • || needs one: Flexible condition.
  • ! flips: The opposite check.
  • Truthy/falsy affect logic: Empty strings and 0 are falsy.
  • + joins strings: Concatenation.
  • Template literals are cleaner: Use backticks and ${ }.

Step-by-step Explanations

How to compare two numbers step by step

  1. Type 10 > 5 in the console.
  2. Press Enter.
  3. See true.
  4. Try 10 < 5 and see false.

How to check equality step by step

  1. Type 5 === 5 and see true.
  2. Type "5" === 5 and see false.
  3. Compare with "5" == 5 which gives true.

How to use && step by step

  1. Write two conditions: age >= 18 and hasID.
  2. Combine with &&: age >= 18 && hasID.
  3. Test with different values in the console.

How to use || step by step

  1. Write two conditions: hasEmail or hasPhone.
  2. Combine with ||: hasEmail || hasPhone.
  3. Test in the console.

How to use template literals step by step

  1. Write a backtick `.
  2. Type your message with ${value} inside.
  3. Close with a backtick `.
  4. Run in the console to see the result.

Real-life Examples

  • Banks: Compare balance to withdrawal.
  • Schools: Compare score to pass mark.
  • Homes: Compare spending to budget.
  • Shops: Compare stock to reorder level.
  • Web apps: Compare passwords and emails.

Nigerian Examples

  • Lagos banks: balance >= amount for transfers.
  • Abuja schools: score >= 50 to pass.
  • Port Harcourt shops: stock <= 10 to reorder.
  • Onitsha traders: price && quantity to check before selling.
  • Kano fintechs: amount > 0 && isVerified to send money.

Fun Examples Children Can Relate To

  • Games: score >= 100 means you win.
  • Snacks: money >= price means you can buy.
  • Toys: toys !== 0 means you still have toys.
  • Pets: isHungry && hasFood means feed the pet.
  • Reading: pages <= 10 means almost done.

Everyday Examples

  • Shopping: money >= total means you can pay.
  • Budget: expenses <= income means safe.
  • Time: hour < 12 means morning.
  • Cooking: water === 2 means add water.
  • Travel: distance > 100 means take the bus.

Parent Tips

  • Show how comparisons appear in real life.
  • Encourage testing with the console.
  • Explain === vs == in simple words.
  • Practice with shopping lists or budgets.
  • Praise curiosity and questions.
  • Read JavaScript articles together.
  • Keep sessions short.
  • Celebrate small wins.
  • Let them teach you.
  • Support their learning journey.

Interesting Facts

  • === was introduced to fix the confusion from ==.
  • NaN is not equal to itself (NaN === NaN is false!).
  • "" is falsy, "0" is truthy.
  • Template literals were added in 2015.
  • ! can be used twice: !!value gives true/false.
  • && returns the second value if the first is truthy.
  • || returns the first truthy value.
  • Nigerian fintechs use these operators in every transaction.

Did You Know?

  • Did you know 0 == "0" is true?
  • Did you know 0 === "0" is false?
  • Did you know [] == false is true?
  • Did you know null == undefined is true?
  • Did you know template literals can span multiple lines?
  • Did you know `${1+1}` prints 2?
  • Did you know !!"hello" is true?
  • Did you know 0 || 5 gives 5?

Remember This

  • Comparison operators give true/false.
  • === is safer than ==.
  • !== is stricter than !=.
  • > and < compare size.
  • >= and <= include equal.
  • && needs both true.
  • || needs at least one true.
  • ! flips true and false.
  • + joins strings.
  • Template literals are cleaner.

Common Mistakes

  • Using == instead of ===.
  • Using = instead of ===.
  • Confusing && and ||.
  • Forgetting truthy/falsy rules.
  • Forgetting backticks for template literals.
  • Missing $ before { }.
  • Not testing conditions in the console.
  • Deeply nested conditions.

Best Practices

  • Use === and !== instead of == and !=.
  • Name variables clearly.
  • Use parentheses to make logic clear.
  • Test in the console.
  • Use template literals for strings.
  • Avoid deep nesting.
  • Read conditions aloud.
  • Comment tricky logic.
  • Check truthy/falsy carefully.
  • Keep lines short.

Illustrations and Diagrams

Comparison Operators

  ===   equal value + type
  !==   not equal value + type
  >     greater than
  <     less than
  >=    greater or equal
  <=    less or equal
  

Logical AND vs OR

  A && B   → true only if both true
  A || B   → true if at least one true
  

Truthy vs Falsy

  Falsy:  false, 0, "", null, undefined, NaN
  Truthy: everything else
  

Template Literals

  `Hello, ${name}!`

  name = "Ada"
  → "Hello, Ada!"
  

Your Learning Journey

  Module 1: Foundations
       |
       V
  Module 2: Arithmetic & Assignment
       |
       V
  Module 3: Comparison & Logic
       |
       V
  Module 4: Advanced & Certification
       |
       V
  Web Operators Expert 🎉
  

Comparison Tables

== vs ===

Expression== result=== result
5 == 5truetrue
"5" == 5truefalse
0 == falsetruefalse
null == undefinedtruefalse

Logical Operators

ABA && BA || B
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse

Comparison Operators Summary

OperatorMeaningExample
===Equal value & type5 === 5
!==Not equal value & type5 !== "5"
>Greater than10 > 5
<Less than5 < 10
>=Greater or equal10 >= 10
<=Less or equal5 <= 5

String Join Methods

MethodExample
+ operator"Hi " + name
Template literal`Hi ${name}`

Lesson Summaries

Lesson 1: Comparison operators check values and return true/false.

Lesson 2: == checks equality with type conversion.

Lesson 3: === checks equality and type — safer.

Lesson 4: != and !== check if values differ.

Lesson 5: > and < compare bigger and smaller.

Lesson 6: >= and <= include equal.

Lesson 7: Logical operators combine conditions.

Lesson 8: && needs both sides true.

Lesson 9: || is true if at least one side is true.

Lesson 10: ! flips true and false.

Lesson 11: Truthy/falsy affect logical results.

Lesson 12: + joins strings.

Lesson 13: Template literals use backticks and ${ }.

Lesson 14: Common mistakes: == vs ===, && vs ||.

Lesson 15: Best practices: use ===, clear names, test often.

Lesson 16: You now have a full logic toolkit.

End-of-Module Summary

Congratulations! You have finished Module Three of the Operators & Expressions for Web course. You learned comparison operators (==, ===, !=, !==, >, <, >=, <=), logical operators (&&, ||, !), truthy and falsy values, and string operators (+ and template literals). You learned common mistakes and best practices. Most importantly, you can now write JavaScript that decides, reacts, and displays dynamic content. In the next module, you will learn advanced operators and complete your certification project.

Frequently Asked Questions

  1. What is a comparison operator? Checks two values and returns true or false.
  2. What is the difference between == and ===? == converts types; === does not.
  3. What is &&? Logical AND — both sides must be true.
  4. What is ||? Logical OR — at least one side is true.
  5. What is !? Logical NOT — flips true and false.
  6. What are truthy values? Values treated as true in logic.
  7. What are falsy values? Values treated as false: false, 0, "", null, undefined, NaN.
  8. How do I join strings? Use + or template literals.
  9. What is a template literal? A string using backticks and ${ }.
  10. Which equality should I use? Always prefer ===.

Matching Exercises

Match the operator to its meaning.

OperatorMeaning
1. ===A. Logical OR
2. !==B. Strict equality
3. &&C. Strict not equal
4. ||D. Greater than
5. >E. Logical AND

Answers: 1-B, 2-C, 3-E, 4-A, 5-D

Scenario-based Exercises

  1. Scenario: You want to check if two passwords are exactly equal.
    Answer: Use ===.
  2. Scenario: You want to check if a score is at least 50.
    Answer: Use >= 50.
  3. Scenario: You want a message if it is a weekday OR a holiday.
    Answer: Use ||.
  4. Scenario: You want to check if the user is NOT logged in.
    Answer: Use !isLoggedIn.
  5. Scenario: You want to greet the user by name.
    Answer: Use template literals.

Group Activity

Title: “Build a Login Check Together”

Instructions: In groups of 3–4, write JavaScript that checks a username and password against fixed values. Use === for both. Show a welcome message using template literals. Present to the class.

Goal: Practice comparisons, logic, and strings.

Individual Activity

Task: In the browser console, type at least 6 examples:

  • One == comparison.
  • One === comparison.
  • One >= comparison.
  • One && combination.
  • One || combination.
  • One template literal.

Write down each and its result.

Mini Project

Project: “My First Login Check”

Create a small login check in JavaScript:

  • Fix a username and password.
  • Ask the user for input (you can hard-code values).
  • Use === to compare.
  • Show "Welcome" or "Wrong" using template literals.
  • Add a special greeting for the admin.

Example:

  let user = "ada";
  let pass = "1234";

  let enteredUser = "ada";
  let enteredPass = "1234";

  if (enteredUser === user && enteredPass === pass) {
    console.log(`Welcome, ${user}!`);
  } else {
    console.log("Wrong login");
  }
  

Practical Assignment

Assignment: Ask a family member about a rule they use (e.g., shopping budget, chores). Then write JavaScript that:

  1. Checks a condition with === or >=.
  2. Combines two checks with && or ||.
  3. Shows a message using a template literal.
  4. Tests the code in the console.

Submit: Your code and a short explanation.

Key Takeaways

  • Comparison operators give true/false.
  • === is safer than ==.
  • !== is stricter than !=.
  • > and < compare size.
  • >= and <= include equal.
  • && needs both true.
  • || needs at least one true.
  • ! flips true and false.
  • + joins strings.
  • Template literals are cleaner.

Classroom Discussion Questions

  1. Why is === safer than ==?
  2. When would you use && instead of ||?
  3. What is the difference between != and !==?
  4. What does ! do to a value?
  5. What are truthy and falsy values?
  6. How do template literals make strings easier?
  7. What mistakes do beginners make with comparisons?
  8. How do comparisons help in real websites?
  9. What would you build with these operators?
  10. What did Chidi learn from building his login page?

Preparation for Module Four

In Module Four, we will learn advanced operators and complete the certification project. We will cover:

  • Ternary operator (? :)
  • Nullish coalescing (??)
  • Optional chaining (?.)
  • Spread (...) and rest (...)
  • typeof, in, instanceof
  • Bitwise operators
  • The certification project and presentation

To prepare, complete the practical assignment and review the key vocabulary. Practice a few comparisons in the console. Bring your curiosity!

See you in Module Four!


End of Module Three – Operators & Expressions for Web

5

Module Four

Operators & Expressions for Web – Module Four

Module Four: Advanced Operators and Certification – Finishing Your Web Operator Journey

“Operators & Expressions for Web” – Learn how JavaScript thinks and calculates

Module Introduction

Welcome to the final module, young web coder! You have come a very long way. In Module One, you learned what operators and expressions are. In Module Two, you learned arithmetic and assignment operators. In Module Three, you learned comparison, logical, and string operators.

Now it is time to add the final layer: advanced operators and your certification project. You will learn about short, powerful operators that make your code cleaner and smarter: the ternary operator, nullish coalescing, optional chaining, and the spread and rest operators. You will also learn about typeof, in, and instanceof.

Think of this module as learning "power moves" in a video game. Once you know them, you can write less code and do more. At the end, you will build a real web project using everything you learned.

Let’s begin!

Learning Objectives

After finishing this module, you will be able to:

  • Use the ternary operator to make quick decisions.
  • Use the nullish coalescing operator (??).
  • Use optional chaining (?.) safely.
  • Use the spread operator (...) to copy and combine.
  • Use the rest operator (...) to collect values.
  • Use typeof, in, and instanceof to check values.
  • Understand bitwise operators in simple terms.
  • Build a complete certification project using operators.
  • Review everything you learned across all four modules.
  • Plan your next steps as a JavaScript learner.

Warm-up Story: Tunde’s Exam Score App

Tunde is 15 years old and lives in Ibadan. He was building a small website to help his teacher record exam scores. The website needed to show "Pass" or "Fail" based on a student’s score.

At first, he wrote it with a big if-else block:

if (score >= 50) {
  result = "Pass";
} else {
  result = "Fail";
}
  

His teacher said, "Can you make it shorter?" Tunde learned about the ternary operator. He rewrote it as:

result = score >= 50 ? "Pass" : "Fail";
  

His teacher smiled. "Much better!"

Next, Tunde wanted to show a message like "Hello [name]" or "Hello Guest" if no name was entered. He first used if-else. Then he learned about nullish coalescing:

message = "Hello " + (name ?? "Guest");
  

He also learned about optional chaining when his data came from an API. Sometimes a student might not have an email yet, so he wrote:

email = student?.contact?.email;
  

His code never broke again — even when some data was missing.

Finally, Tunde learned the spread operator to combine two lists of students into one:

allStudents = [...classA, ...classB];
  

At the end of the day, his small web app was clean, short, and worked beautifully. His teacher said, "You have become a real JavaScript expert!"

Tunde smiled. Advanced operators had made his code easier and smarter.

Moral of the story: Advanced operators let you do more with less code. They make your programs shorter, safer, and easier to read.

Main Lessons

Lesson 1: The Ternary Operator ( ? : )

Definition: The ternary operator is a short way to write an if-else decision in one line.

Why it is important: It makes your code cleaner and shorter.

Simple explanation: It is like asking "Yes or No?" and giving two answers.

Real-life example: A bank shows "Adult" or "Minor" based on age.

School example: A teacher shows "Pass" or "Fail" based on score.

Home example: A family shows "Rainy" or "Sunny" based on weather.

Nigerian example: A trader shows "Buy" or "Wait" based on price.

Illustration:

condition ? valueIfTrue : valueIfFalse

Example:
score >= 50 ? "Pass" : "Fail"
  

Step-by-step:

  1. Write the condition.
  2. Add a question mark ( ? ).
  3. Write the value if true.
  4. Add a colon ( : ).
  5. Write the value if false.
  6. Store it in a variable or use it directly.

Mini summary: The ternary operator is a short if-else in one line.

Lesson 2: Using the Ternary Operator in Real Code

Definition: In real code, ternary operators often appear in templates, forms, and messages.

Why it is important: It keeps code readable when the choice is simple.

Simple explanation: It is like a shortcut in a video game.

Real-life example: A bank shows "Approved" or "Pending" on a loan.

School example: A teacher shows "Present" or "Absent".

Home example: A family shows "Open" or "Closed" for the shop.

Nigerian example: A trader shows "In Stock" or "Sold Out".

Illustration:

let status = isOpen ? "Open" : "Closed";
let greeting = hour < 12 ? "Good morning" : "Good afternoon";
  

Step-by-step:

  1. Pick a simple true/false decision.
  2. Write it with a ternary.
  3. If it becomes too long, go back to if-else.

Mini summary: Use ternary operators for short, simple decisions.

Lesson 3: The Nullish Coalescing Operator ( ?? )

Definition: The nullish coalescing operator ( ?? ) gives a fallback value when the main value is null or undefined.

Why it is important: It prevents errors when data is missing.

Simple explanation: It is like saying, "If this is empty, use that instead."

Real-life example: A bank shows "Unknown" if a customer’s name is missing.

School example: A teacher shows "No score" if a student is missing.

Home example: A family shows "Guest" if no name is entered.

Nigerian example: A trader shows "No price" if a product has no price set.

Illustration:

let name = enteredName ?? "Guest";
let price = productPrice ?? 0;
  

Step-by-step:

  1. Write the value that might be missing.
  2. Add ??
  3. Add the fallback value.
  4. Store in a variable or use directly.

Mini summary: The ?? operator gives a safe fallback for missing values.

Lesson 4: Nullish ( ?? ) vs OR ( || )

Definition: The OR operator ( || ) also gives a fallback, but it triggers on any "falsy" value, not just null or undefined.

Why it is important: Using the wrong one can cause bugs, especially with 0 or "".

Simple explanation: || triggers on many "empty" things. ?? triggers only on truly missing things.

Real-life example: A bank shows "0" for a customer with zero balance, not "Not available".

School example: A teacher shows "0" for a score of zero, not "No score".

Home example: A family shows "0" for items sold, not "No items".

Nigerian example: A trader shows "₦0" for a free product, not "No price".

Illustration:

0 || "default"  →  "default"   (wrong for numbers)
0 ?? "default"  →  0           (correct)
  

Step-by-step:

  1. Ask: Is 0 or "" a valid value?
  2. If yes, use ??
  3. If no, || is fine.

Mini summary: Use ?? when 0 or empty strings are valid values.

Lesson 5: Optional Chaining ( ?. )

Definition: Optional chaining ( ?. ) lets you safely access properties inside objects that might be missing.

Why it is important: It prevents your code from crashing.

Simple explanation: It is like asking, "Does this exist? If yes, continue. If no, stop."

Real-life example: A bank checks a customer’s phone before sending an SMS.

School example: A teacher checks a student’s email before sending notes.

Home example: A family checks a relative’s address before sending a card.

Nigerian example: A trader checks a product’s price before calculating total.

Illustration:

student?.contact?.email

If student is undefined → returns undefined (no crash)
  

Step-by-step:

  1. Write the object.
  2. Add ?.
  3. Add the next property.
  4. Repeat as needed.

Mini summary: Optional chaining (?.) keeps your code safe when data is missing.

Lesson 6: The Spread Operator ( ... )

Definition: The spread operator ( ... ) "spreads" the items of an array or object into another.

Why it is important: It makes copying and combining easy.

Simple explanation: It is like pouring all the items from one bag into another bag.

Real-life example: A bank combines two customer lists.

School example: A teacher combines two class lists.

Home example: A family combines two shopping lists.

Nigerian example: A trader combines stock from two shops.

Illustration:

const all = [...classA, ...classB];
const person = { ...ada, city: "Enugu" };
  

Step-by-step:

  1. Write [ ...array1, ...array2 ].
  2. Or write { ...object1, key: value }.
  3. Use to copy or extend.

Mini summary: The spread operator spreads values into new arrays or objects.

Lesson 7: The Rest Operator ( ... )

Definition: The rest operator ( ... ) collects many values into one array.

Why it is important: It lets functions take unlimited arguments.

Simple explanation: It is like gathering scattered toys into one box.

Real-life example: A bank accepts any number of deposits.

School example: A teacher collects scores for any number of tests.

Home example: A family collects any number of shopping items.

Nigerian example: A trader adds up any number of items to a cart.

Illustration:

function sum(...numbers) {
  return numbers.reduce((a, b) => a + b, 0);
}

sum(1, 2, 3, 4); // 10
  

Step-by-step:

  1. Write function name.
  2. Add (...name) as a parameter.
  3. Use it like an array.
  4. Call with any number of values.

Mini summary: The rest operator collects values into an array.

Lesson 8: The typeof Operator

Definition: typeof tells you what kind of value something is.

Why it is important: It helps you check data before using it.

Simple explanation: typeof is like asking "What is this?"

Real-life example: A bank checks if a value is a number before calculating interest.

School example: A teacher checks if a score is a number before grading.

Home example: A family checks if a price is a number before budgeting.

Nigerian example: A trader checks if a quantity is a number before selling.

Illustration:

typeof "Hello"  →  "string"
typeof 42       →  "number"
typeof true     →  "boolean"
typeof {}       →  "object"
typeof []       →  "object" (special case)
  

Mini summary: typeof tells you the data type of a value.

Lesson 9: The in Operator

Definition: The in operator checks if a property exists in an object.

Why it is important: It helps you avoid missing data errors.

Simple explanation: It is like asking, "Is this key inside the box?"

Real-life example: A bank checks if a customer record has an email field.

School example: A teacher checks if a student record has a phone field.

Home example: A family checks if a recipe has a sugar field.

Nigerian example: A trader checks if a product has a price field.

Illustration:

"email" in customer  →  true or false
"price" in product   →  true or false
  

Mini summary: The in operator checks if a property exists in an object.

Lesson 10: The instanceof Operator

Definition: instanceof checks if an object was created by a certain class or constructor.

Why it is important: It confirms what type of object you have.

Simple explanation: It is like asking, "Was this made by this factory?"

Real-life example: A bank checks if an object is a Date.

School example: A teacher checks if an object is a Student object.

Home example: A family checks if an object is a Recipe.

Nigerian example: A trader checks if an object is a Product.

Illustration:

new Date() instanceof Date  →  true
[] instanceof Array          →  true
{} instanceof Object         →  true
  

Mini summary: instanceof tells you what class an object came from.

Lesson 11: Bitwise Operators (Quick Intro)

Definition: Bitwise operators work on the binary form (1s and 0s) of numbers.

Why it is important: They are fast, but mostly used in advanced code.

Simple explanation: It is like working with the smallest pieces of a number.

Real-life example: A bank uses bitwise flags for account settings.

School example: A teacher uses flags to mark which students are present.

Home example: A family uses flags for chores done or not done.

Nigerian example: A trader uses flags for "paid or unpaid" orders.

Illustration:

5 & 3   →  1
5 | 3   →  7
5 ^ 3   →  6
~5      →  -6
5 << 1  →  10
5 >> 1  →  2
  

Mini summary: Bitwise operators work on the binary form of numbers. Beginner coders rarely need them.

Lesson 12: Combining Advanced Operators

Definition: You can combine operators to write short, powerful code.

Why it is important: It shows real-world coding skill.

Simple explanation: It is like using several power moves in a game.

Real-life example: A bank formats a greeting using ternary and ??.

School example: A teacher shows status using ternary and ?.

Home example: A family shows a note using ?? and ?.

Nigerian example: A trader shows a price using ?? and ?.

Illustration:

const display = user?.name ?? "Guest";
const status  = score >= 50 ? "Pass" : "Fail";
const label   = price > 0 ? "₦" + price : "Free";
  

Mini summary: Combining operators makes powerful, clean code.

Lesson 13: Common Mistakes with Advanced Operators

Definition: Mistakes happen. Knowing them helps you avoid them.

Why it is important: Advanced operators can cause tricky bugs.

Simple explanation: Like pressing the wrong button on a game controller.

Real-life example: A bank uses || instead of ?? and shows "0" as "Not available".

School example: A teacher uses = instead of === and gets wrong results.

Home example: A family uses ?. incorrectly and hides real errors.

Nigerian example: A trader uses ?? when || was needed and misses a valid price.

Table of common mistakes:

MistakeWhat HappensHow to Fix
Using || instead of ??Zero and "" treated as missingUse ?? for valid zeros
Using = instead of ===Assignment instead of comparisonUse === for comparison
Overusing ?.Hides real bugsOnly use when data may be missing
Nested ternariesHard to readUse if-else for complex logic
Forgetting () in spreadSyntax errorUse ... correctly
Confusing rest and spreadWrong dataRemember context

Mini summary: Common mistakes: using || instead of ??, overusing ?., and nesting ternaries.

Lesson 14: Best Practices for Advanced Operators

Definition: Best practices are good habits that make your code clean and safe.

Why it is important: Good habits prevent bugs and make code easier for others to read.

Simple explanation: Like keeping your room clean — easier to find things.

Real-life example: A bank writes clean, safe code.

School example: A student writes neat, easy-to-read code.

Home example: A family keeps a shared budget sheet tidy.

Nigerian example: A business writes clean code that other developers can maintain.

List of best practices:

  • Use === and !== instead of == and !=.
  • Use ?? for valid zeros or empty strings.
  • Use ?. only when data might be missing.
  • Keep ternaries short (one condition).
  • Use spread to avoid mutating original data.
  • Use rest for flexible functions.
  • Use typeof, in, and instanceof for safe checks.
  • Format your code clearly.
  • Add comments when logic is tricky.
  • Test your code with real values.

Mini summary: Best practices: use strict equality, ?? for zeros, and keep code readable.

Lesson 15: Preparing for the Certification Project

Your certification project brings everything together.

Project idea: Build a small interactive web page using every kind of operator you learned.

Steps:

  1. Choose a simple idea (calculator, form validator, quiz).
  2. Plan the page in plain English.
  3. Write HTML structure.
  4. Add CSS for a clean look.
  5. Write JavaScript using all operators.
  6. Test with different values.
  7. Add comments to explain your code.
  8. Present to your class.

Illustration:

  Project Flow:

  Idea
    |
    V
  Plan
    |
    V
  HTML + CSS + JS
    |
    V
  Test
    |
    V
  Present 🎉
  

Mini summary: The certification project uses every operator you learned.

Lesson 16: Reviewing Everything You Learned

You have learned a lot. Let’s review.

Module One: What operators and expressions are.

Module Two: Arithmetic and assignment operators.

Module Three: Comparison, logical, and string operators.

Module Four: Advanced operators and certification project.

Illustration:

  Your Skills:

  +----------------+
  | Expressions    |
  +----------------+
  +----------------+
  | Arithmetic     |
  +----------------+
  +----------------+
  | Comparison     |
  +----------------+
  +----------------+
  | Advanced       |
  +----------------+
  +----------------+
  | Certification  |
  +----------------+
  

Mini summary: You have mastered all levels of JavaScript operators.

Lesson 17: Your Certification and Beyond

Your certification is proof that you are a Web Operators Expert.

Next steps:

  • Complete your certification project.
  • Practice on websites like Codewars or freeCodeCamp.
  • Build more small web apps.
  • Learn about functions and objects next.
  • Help others learn JavaScript.
  • Keep coding every day.

Illustration:

  Certification
       |
       V
  Portfolio
       |
       V
  Share with others
       |
       V
  Help others learn
       |
       V
  Apply skills
       |
       V
  Web Operators Expert 🎉
  

Mini summary: Your certification opens doors to more advanced JavaScript.

Key Vocabulary

WordSimple Definition
TernaryShort if-else in one line.
Nullish Coalescing (??)Fallback for null or undefined.
Optional Chaining (?.)Safe access to possibly missing data.
Spread (...)Spreads values into a new array or object.
Rest (...)Collects many values into one array.
typeofTells the data type of a value.
inChecks if a property exists in an object.
instanceofChecks the class of an object.
BitwiseWorks on binary digits (1s and 0s).
FalsyValues treated as false in logic.
TruthyValues treated as true in logic.
BugA mistake in code.
Strict Equality (===)Checks value AND type.
ImmutableCannot be changed.
FallbackBackup value.

Important Concepts

  • Ternary makes decisions short: One line, two answers.
  • ?? protects missing values: Fallback for null and undefined.
  • || is different from ??: || triggers on many falsy values.
  • ?. prevents crashes: Safe access to missing data.
  • Spread copies and combines: Arrays and objects.
  • Rest collects values: Flexible functions.
  • typeof checks types: Safe coding.
  • in checks properties: Avoid missing keys.
  • instanceof checks classes: Know your objects.
  • Bitwise is advanced: Not needed for most beginners.

Step-by-step Explanations

How to use the ternary operator step by step

  1. Write the condition.
  2. Add ? and the true value.
  3. Add : and the false value.
  4. Store or use the result.

How to use ?? step by step

  1. Write the value that might be missing.
  2. Add ?? and the fallback value.
  3. Use in a variable or directly.

How to use ?. step by step

  1. Write the object.
  2. Add ?. before each possibly missing property.
  3. Add a fallback if needed with ??.

How to use spread step by step

  1. Write a new array or object.
  2. Add ... followed by the source.
  3. Add extra items if needed.

How to use rest step by step

  1. Write a function.
  2. Add ...name as parameter.
  3. Treat name as an array inside the function.
  4. Call with any number of values.

Real-life Examples

  • Banks: Use ternary for status, ?? for missing data.
  • Schools: Use ternary for grades, ?. for missing student info.
  • Homes: Use ?? for default names, spread for combining lists.
  • Startups: Use rest for flexible functions.
  • Web apps: Combine everything in dashboards and forms.

Nigerian Examples

  • Lagos fintechs: Use ?? for missing balance data.
  • Abuja restaurants: Use ternary for "Open/Closed".
  • Port Harcourt tailors: Use rest to sum multiple orders.
  • Onitsha traders: Use spread to merge stock lists.
  • Kano schools: Use ?. to safely show student data.

Fun Examples Children Can Relate To

  • Games: Ternary to show "Win" or "Lose".
  • Snacks: ?? to show "No snack chosen".
  • Toys: Spread to combine two toy lists.
  • Pets: ?. to safely show pet info.
  • Reading: Rest to count many books.

Everyday Examples

  • Shopping: ?? for "0 items" fallback.
  • Budget: Ternary for "Within budget / Over budget".
  • Family: Spread to combine to-do lists.
  • Homework: ?. for safe data access.
  • Travel: Rest to sum costs.

Parent Tips

  • Encourage your child to write short, clear code.
  • Show how ternary and ?? appear in real apps.
  • Discuss how ?. keeps code safe.
  • Practice simple examples together.
  • Celebrate small coding wins.
  • Read JavaScript articles together.
  • Let them teach you what they learned.
  • Keep sessions short and fun.
  • Encourage reading other people’s code.
  • Support their certification journey.

Interesting Facts

  • ?? was added to JavaScript in 2020.
  • ?. helps prevent "cannot read property" errors.
  • Spread and rest use the same symbol (...).
  • typeof [] returns "object" — a famous quirk.
  • Bitwise operators work on 32-bit numbers.
  • Nested ternaries are often discouraged.
  • Most modern web apps use these operators.
  • Nigerian developers use them daily in fintech apps.

Did You Know?

  • Did you know ?. saves you from writing long if checks?
  • Did you know ?? is safer than || for numbers?
  • Did you know spread creates a copy — not the original?
  • Did you know rest replaced the old "arguments" object?
  • Did you know instanceof works with custom classes?
  • Did you know the ternary operator is the only JS operator with three parts?
  • Did you know 0 ?? 5 returns 0?
  • Did you know 0 || 5 returns 5?

Remember This

  • Ternary = short if-else.
  • ?? = fallback for null and undefined.
  • || = fallback for many falsy values.
  • ?. = safe access to missing data.
  • Spread = copy and combine.
  • Rest = collect values.
  • typeof = check type.
  • in = check property.
  • instanceof = check class.
  • Bitwise = advanced only.

Common Mistakes

  • Using || instead of ??.
  • Using = instead of ===.
  • Overusing ?.
  • Nesting too many ternaries.
  • Forgetting ... in spread.
  • Confusing rest with spread.
  • Not testing with real values.
  • Not reading error messages.

Best Practices

  • Use === and !==.
  • Use ?? for valid zeros and empty strings.
  • Use ?. only when data might be missing.
  • Keep ternaries short.
  • Use spread to avoid mutating data.
  • Use rest for flexible functions.
  • Use typeof, in, instanceof for safety.
  • Format your code clearly.
  • Add comments for tricky logic.
  • Test your code with real values.

Illustrations and Diagrams

Ternary Decision

  score >= 50
     /    \
   Yes     No
    |       |
  "Pass"  "Fail"
  

?? Fallback Flow

  value ?? fallback

  value is null/undefined → use fallback
  otherwise → use value
  

Optional Chaining

  user?.profile?.name
      |
      V
  Returns undefined if any part is missing
  

Spread vs Rest

  Spread:  [ ...a, ...b ]   (out)
  Rest:    (...values)      (in)
  

Your Learning Journey

  Module 1: Foundations
       |
       V
  Module 2: Arithmetic & Assignment
       |
       V
  Module 3: Comparison & Logic
       |
       V
  Module 4: Advanced & Certification
       |
       V
  Web Operators Expert 🎉
  

Comparison Tables

?? vs ||

Value?? Result|| Result
00Fallback
""""Fallback
nullFallbackFallback
undefinedFallbackFallback

Spread vs Rest

FeatureSpreadRest
DirectionOutwardInward
UseCopy/combineCollect
Example[...a, ...b]function(...args)

typeof Results

Valuetypeof
"hi"string
5number
trueboolean
[]object
nullobject

Advanced Operator Uses

OperatorUse Case
?Quick if-else
??Safe fallback
?.Safe access
...Spread / rest
inCheck property
instanceofCheck class

Lesson Summaries

Lesson 1: Ternary operator is a short if-else in one line.

Lesson 2: Ternary is best for simple true/false decisions.

Lesson 3: ?? gives a fallback for null or undefined.

Lesson 4: Use ?? instead of || for valid zeros and empty strings.

Lesson 5: ?. safely accesses possibly missing data.

Lesson 6: Spread copies and combines arrays and objects.

Lesson 7: Rest collects values into one array.

Lesson 8: typeof tells you the type of a value.

Lesson 9: in checks if a property exists in an object.

Lesson 10: instanceof checks the class of an object.

Lesson 11: Bitwise operators work on binary numbers.

Lesson 12: Combining operators makes short, powerful code.

Lesson 13: Common mistakes: || vs ??, too many ternaries.

Lesson 14: Best practices: strict equality, ?? for zeros, keep it readable.

Lesson 15: Certification project uses every operator.

Lesson 16: Review of all four modules.

Lesson 17: Certification opens doors to more JavaScript.

End-of-Module Summary

Congratulations! You have finished Module Four and the entire Operators & Expressions for Web course. You learned the ternary operator, nullish coalescing, optional chaining, spread, rest, typeof, in, instanceof, and even bitwise operators. You learned common mistakes and best practices. You prepared and completed your certification project. Most importantly, you are now a Web Operators Expert. Keep coding, keep learning, and keep building!

Frequently Asked Questions

  1. What is the ternary operator? A short if-else in one line.
  2. What is ?? used for? Fallback for null and undefined.
  3. What is ?. used for? Safe access to possibly missing data.
  4. What is spread? Spreading values into a new array or object.
  5. What is rest? Collecting many values into one array.
  6. What does typeof do? Tells you the data type of a value.
  7. What does in do? Checks if a property exists in an object.
  8. What does instanceof do? Checks the class of an object.
  9. What are bitwise operators? Operators on binary numbers.
  10. Do I need bitwise as a beginner? No, they are advanced.

Matching Exercises

Match the operator to its meaning.

OperatorMeaning
1. ? :A. Safe access to missing data
2. ??B. Short if-else
3. ?.C. Fallback for null/undefined
4. ... (in front)D. Collect values
5. ... (in function)E. Spread values

Answers: 1-B, 2-C, 3-A, 4-E, 5-D

Scenario-based Exercises

  1. Scenario: You need to show "Pass" or "Fail" in one line.
    Answer: Use the ternary operator.
  2. Scenario: A customer’s name may be missing.
    Answer: Use ?? with "Guest".
  3. Scenario: You’re not sure if a student object has an email.
    Answer: Use ?. safely.
  4. Scenario: You want to combine two student lists.
    Answer: Use spread.
  5. Scenario: A function may receive any number of scores.
    Answer: Use rest.

Group Activity

Title: “Build a Mini App Together”

Instructions: In groups of 3–4, choose a small web idea (calculator, quiz, form). Plan which operators you will use. Write at least one example of ternary, ??, ?., spread, and rest. One person writes HTML, one writes JS, one tests, one presents. Share with the class.

Goal: Practice using advanced operators in a real project.

Individual Activity

Task: Write short JavaScript code that uses:

  • One ternary operator.
  • One ?? fallback.
  • One ?. check.
  • One spread example.
  • One rest example.

Hint: Keep each example to 2–3 lines.

Mini Project

Project: “My First Advanced Operators Page”

Build a small web page with JavaScript that:

  • Shows "Pass" or "Fail" using ternary.
  • Uses ?? for a default name.
  • Uses ?. to safely access a property.
  • Uses spread to combine two arrays.
  • Uses rest to sum values.

Example:

  let score = 65;
  console.log(score >= 50 ? "Pass" : "Fail"); // Pass

  let user = { name: "Ada" };
  console.log(user?.contact?.email ?? "No email");

  let a = [1, 2], b = [3, 4];
  console.log([...a, ...b]); // [1,2,3,4]
  

Practical Assignment

Assignment: Build the certification project — a small interactive web page that uses at least six different operators from the entire course. Include:

  1. Arithmetic and assignment operators.
  2. Comparison and logical operators.
  3. Ternary operator.
  4. Nullish coalescing operator.
  5. Optional chaining.
  6. Spread or rest.

Write clean code with comments and present it to your class.

Submit: Your HTML, CSS, and JavaScript files with your presentation.

Key Takeaways

  • Ternary = short if-else.
  • ?? = fallback for null and undefined.
  • || = fallback for many falsy values.
  • ?. = safe access to missing data.
  • Spread = copy and combine.
  • Rest = collect values.
  • typeof = check type.
  • in = check property.
  • instanceof = check class.
  • Bitwise = advanced only.

Classroom Discussion Questions

  1. When should you use ternary instead of if-else?
  2. Why is ?? safer than || for numbers?
  3. How does ?. protect your code?
  4. What is the difference between spread and rest?
  5. Why is typeof useful in JavaScript?
  6. What does the in operator check?
  7. What does instanceof check?
  8. Are bitwise operators useful for beginners?
  9. What mistakes do coders make with these operators?
  10. What did Tunde learn from building his exam score app?

Next Steps After Certification

Congratulations! You have completed the entire Operators & Expressions for Web course. Here are some next steps you can take:

  • Practice: Write small programs using all operators.
  • Build: Create your own interactive web pages.
  • Explore: Learn functions, objects, and arrays in depth.
  • Join: Use freeCodeCamp, Codewars, or MDN to keep learning.
  • Share: Teach others what you have learned.
  • Keep coding: Coding is a skill that grows with practice.

Remember, this is just the beginning. You are now a Web Operators Expert. Keep coding, keep learning, and keep building!


End of Module Four – Operators & Expressions for Web

🎉 Congratulations! You have completed the entire Operators & Expressions for Web course! 🎉

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, pass the exam, and unlock Practice Tools plus a verified certificate with your name on it — ₦4,000/month.

🎓 Sign Up & Unlock for ₦4,000/month
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - try them free for 7 days, no card required.
→