← Variables and Data Types for Web · Lesson 1 of 5

Course Outline

📖 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

Variables & Data Types for Web · Course Outline
📦 beginner course · 2026

Variables & Data Types for Web

⚡ let · const · strings · numbers · objects 🧠 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 Variables & Data Types
Understand what variables and data types are, and why every web page depends on them.
  • What is a variable?
  • What is a data type?
  • Why variables matter
  • Naming rules & conventions
  • Declaring your first variable
  • Using the browser console
✓ outcome Declare variables and identify their data types in JavaScript
Module 2 Strings, Numbers & Booleans
Master the three most common data types used on every website.
  • Strings (text)
  • Numbers (integers & decimals)
  • Booleans (true/false)
  • String methods & concatenation
  • Number methods & Math
  • Template literals
✓ outcome Build a small text-and-number based web calculator
Module 3 Objects, Arrays & Special Types
Learn how to store and organize many values with objects, arrays, null, and undefined.
  • Objects (key-value pairs)
  • Arrays (lists of values)
  • Null & undefined
  • Nested objects and arrays
  • Accessing and updating values
  • JSON basics
✓ outcome Build a simple contact list using objects and arrays
Module 4 Type Conversion, Scope & Certification Project
Learn type conversion, scope, and complete a real web-based project.
  • Type conversion (Number, String, Boolean)
  • typeof & type checking
  • let vs const vs var
  • Scope (block & global)
  • Hoisting basics
  • Certification project & presentation
✓ outcome Complete a full web project using variables and all data types

📦 certification project beginner

"Student Profile Web App" — build a small web app using HTML, CSS, and JavaScript that stores student data (name, age, scores, subjects, hobbies) using variables, strings, numbers, booleans, objects, and arrays. Display the data neatly on a web page.

🎯 portfolio piece · peer review · certification


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

Module One

Variables & Data Types for Web – Module One

Module One: Introduction to Variables and Data Types – Giving Names to Information

“Variables & Data Types for Web” – Learn how JavaScript remembers information

Module Introduction

Welcome, young web coder! Have you ever wondered how a website remembers your name after you log in? Or how a game knows your score? The answer is variables and data types.

A variable is a named container that holds a value. A data type tells the computer what kind of value it is — a number, text, true/false, or something else. Every website you use, from Facebook to your school portal, uses variables and data types thousands of times.

In this module, we will learn what variables and data types are, how to create them, and how to use them in JavaScript. We will use the browser console to test our code. 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 a variable is in your own words.
  • Explain what a data type is in your own words.
  • Declare variables using let and const.
  • Name variables correctly.
  • Identify common data types in JavaScript.
  • Use the browser console to test variables.
  • Understand why variables matter on the web.
  • Give Nigerian examples of variables in real life.
  • Think like a programmer when reading code.
  • Complete a mini project and practical assignment.

Warm-up Story: Ada’s School Registration Form

Ada is 13 years old and lives in Lagos. Her school asked every student to fill a registration form. The form asked for name, age, class, and whether the student had paid fees.

Ada looked at the form and thought, "This is exactly what variables do in JavaScript!" She opened the browser console and typed:

let name = "Ada";
let age = 13;
let studentClass = "JSS3";
let hasPaidFees = true;
  

Each line created a variable. The variable name held the text "Ada". The variable age held the number 13. The variable studentClass held the text "JSS3". The variable hasPaidFees held the value true.

Ada then typed:

console.log("Welcome, " + name);
console.log("You are " + age + " years old.");
  

The console printed:

Welcome, Ada
You are 13 years old.
  

Ada smiled. She realized that a form is just a set of variables. Every website she had ever used was built the same way — with variables holding information.

From that day, Ada saw the world differently. A shop is a variable. A price is a variable. A customer name is a variable. Her mother’s shop list could be turned into code!

Moral of the story: Variables are named containers for values. Data types tell us what kind of value is inside. Together, they let websites remember and use information.

Main Lessons

Lesson 1: What is a Variable?

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

Why it is important: Variables let your code remember information and reuse it.

Simple explanation: A variable is like a labeled box. You write a name on the box, put something inside, and use it later.

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

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

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

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

Illustration:

  Variable = Labeled Box

  +-----------+
  | name: Ada |
  +-----------+

  +-----------+
  | age: 13   |
  +-----------+
  

Mini summary: A variable is a labeled container that holds a value.

Lesson 2: Why Do We Need Variables?

Definition: Variables store information so we can use it again and again.

Why it is important: Without variables, we would have to type the same value many times, and if it changed, we would have to change it everywhere.

Simple explanation: It is like having a labelled jar of sugar in the kitchen. You use it many times without buying new sugar each time.

Real-life example: A bank keeps a customer balance in a variable and updates it with every transaction.

School example: A teacher keeps a class list in a variable and adds new students.

Home example: A family keeps a shopping list in a variable and adds items.

Nigerian example: A trader keeps the price of goods in variables.

Illustration:

  Without variables:  "Ada" ... "Ada" ... "Ada" (repeat, repeat)
  With variables:     let name = "Ada";
                      console.log(name);
  

Mini summary: Variables save time and keep information organized.

Lesson 3: Creating Your First Variable

Definition: Creating a variable means giving it a name and a value in code.

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

Simple explanation: You write let or const, then a name, then an equals sign, then a value.

Real-life example: A bank creates a variable balance = 5000.

School example: A teacher creates score = 90.

Home example: A family creates shoppingTotal = 2500.

Nigerian example: A trader creates priceOfRice = 3000.

Illustration:

  let name = "Ada";
  let age = 13;
  let hasPaidFees = 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: Creating a variable means giving it a name and a value.

Lesson 4: let vs const

Definition: let creates a variable whose value can change. const creates a variable whose value cannot change.

Why it is important: Some values should stay the same. Others change.

Simple explanation: let is a whiteboard you can erase and rewrite. const is a stone tablet you write once.

Real-life example: A bank uses let balance (it changes) and const bankName (it does not).

School example: A teacher uses let score and const schoolName.

Home example: A family uses let monthlySpending and const homeAddress.

Nigerian example: A trader uses let stock and const shopName.

Illustration:

  let age = 13;
  age = 14;      // OK

  const birthday = "1 Jan";
  birthday = "2 Jan";   // ERROR
  

Mini summary: Use let for changing values and const for fixed values.

Lesson 5: Naming Your Variables

Definition: Variable names are the labels you give your containers.

Why it is important: Clear names make code easy to read.

Simple explanation: Names should describe what is inside.

Real-life example: A bank calls it balance, not b.

School example: A teacher calls it mathScore, not m.

Home example: A family calls it monthlyBudget, not mb.

Nigerian example: A trader calls it totalSales, not ts.

Illustration:

  Good:  let customerName = "Ada";
  Good:  let priceOfRice = 3000;
  Bad:   let x = "Ada";
  Bad:   let p = 3000;
  

Step-by-step:

  1. Use letters, numbers, _, and $.
  2. Do not start with a number.
  3. Use camelCase (e.g., totalSales).
  4. Do not use reserved words like let.
  5. Make names meaningful.

Mini summary: Use clear, descriptive names in camelCase.

Lesson 6: What is a Data Type?

Definition: A data type tells the computer what kind of value a variable holds.

Why it is important: Different types behave differently.

Simple explanation: A data type is like a container: a bottle for water, a box for shoes.

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

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

Home example: A family stores ages as numbers and addresses 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
  Object:   { name: "Ada" }
  Array:    [1, 2, 3]
  

Mini summary: A data type tells the computer what kind of value a variable holds.

Lesson 7: The Number Type

Definition: The number type is used for numeric values.

Why it is important: Numbers are used for math and counting.

Simple explanation: Numbers can be whole or decimal.

Real-life example: A bank uses numbers for account balances.

School example: A teacher uses numbers for scores.

Home example: A family uses numbers for prices.

Nigerian example: A trader uses numbers for quantities and prices.

Illustration:

  let age = 13;         // whole number
  let price = 3000.50;  // decimal
  let score = 90;

  typeof age     →  "number"
  

Mini summary: Numbers are used for math and values like age, price, score.

Lesson 8: The String Type

Definition: A string is a piece of text inside quotes.

Why it is important: Text is everywhere on the web — names, messages, titles.

Simple explanation: A string is any text wrapped in quotes.

Real-life example: A bank stores customer names as strings.

School example: A teacher stores student names as strings.

Home example: A family stores addresses as strings.

Nigerian example: A trader stores product names as strings.

Illustration:

  let name = "Ada";
  let city = "Lagos";
  let message = "Welcome!";

  typeof name    →  "string"
  

Mini summary: Strings are text inside quotes.

Lesson 9: The Boolean Type

Definition: A boolean is a value that is either true or false.

Why it is important: Booleans control decisions on websites.

Simple explanation: A boolean answers yes/no questions.

Real-life example: A bank checks if a customer has paid fees (true/false).

School example: A teacher checks if a student is present (true/false).

Home example: A family checks if the door is locked (true/false).

Nigerian example: A trader checks if a product is in stock (true/false).

Illustration:

  let hasPaidFees = true;
  let isOpen = false;

  typeof hasPaidFees  →  "boolean"
  

Mini summary: Booleans are true or false values used for decisions.

Lesson 10: Other Common Data Types

Definition: JavaScript has more types: null, undefined, object, array.

Why it is important: Real data is not just numbers and text.

Simple explanation: Each type is a special tool for a special job.

Real-life example: A bank uses objects to store customer records.

School example: A teacher uses arrays to store class scores.

Home example: A family uses arrays for shopping lists.

Nigerian example: A trader uses objects for product info.

Illustration:

  null:       let price = null;         // empty on purpose
  undefined:  let score;                // not set yet
  object:     let student = { name: "Ada" };
  array:      let scores = [85, 92, 78];
  

Mini summary: JavaScript also has null, undefined, objects, and arrays.

Lesson 11: Using typeof to Check Types

Definition: typeof is an operator that tells you the type of a value.

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 adding interest.

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

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 undefined →  "undefined"
  

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

Lesson 12: The Browser Console

Definition: The browser console is a tool for testing JavaScript.

Why it is important: It is a safe place to try variables and see results instantly.

Simple explanation: The console is like a notebook that answers back.

Real-life example: A developer tests variables before adding them to a page.

School example: A student tests let age = 13; in the console.

Home example: A family tests a shopping total.

Nigerian example: A trader tests the total price of goods.

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 let name = "Ada"; and press Enter.
  5. Type name and press Enter to see the value.

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

Lesson 13: Variables on Real Websites

Definition: Every website uses variables to remember user data.

Why it is important: Variables make websites personalized.

Simple explanation: When a website says "Hello, Ada", it used a variable.

Real-life example: A bank shows your balance using a variable.

School example: A school portal shows your name using a variable.

Home example: A shopping site shows your cart total using a variable.

Nigerian example: A fintech app shows your balance using a variable.

Illustration:

  Website Flow:

  User logs in → name stored in variable → "Hello, Ada" shown 🎉
  

Mini summary: Real websites use variables to greet and remember users.

Lesson 14: Common Mistakes with Variables

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

Why it is important: Small mistakes can stop your code.

Simple explanation: Like writing the wrong label on a box.

Real-life example: A bank mixes up two account balances.

School example: A teacher swaps two students’ scores.

Home example: A family reads the wrong shopping total.

Nigerian example: A trader quotes the wrong price.

Table of common mistakes:

MistakeWhat HappensHow to Fix
Starting name with a numberSyntax errorStart with a letter
Using reserved wordsSyntax errorPick another name
Reassigning constErrorUse let if value changes
Mixing typesWrong resultUse correct type
Forgetting semicolonErrorAdd ; at the end
Using undefined valueundefined resultCheck before use

Mini summary: Common mistakes: bad names, mixing types, missing semicolons.

Lesson 15: Best Practices for Variables and Types

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

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

Simple explanation: Like keeping a tidy desk.

Real-life example: A bank writes clean code so any developer can read 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 const by default.
  • Use let only when the value changes.
  • Use clear, meaningful names in camelCase.
  • Use the right data type.
  • Check types with typeof.
  • Test in the browser console.
  • Keep one purpose per variable.
  • Avoid very long names or very short names.
  • Add comments for tricky values.
  • Read error messages carefully.

Mini summary: Best practices: const by default, clear names, correct types.

Lesson 16: Putting It All Together – Your Variable Toolkit

You now have a strong foundation in variables and data types.

What you learned:

  • What a variable is
  • Why variables matter
  • How to create variables
  • let vs const
  • Naming rules
  • Common data types
  • typeof
  • The browser console
  • Common mistakes and best practices

Next steps: In Module Two, you will learn about strings, numbers, and booleans in depth.

Illustration:

  Your Learning Journey:

  Module 1: Foundations
       |
       V
  Module 2: Strings, Numbers, Booleans
       |
       V
  Module 3: Objects, Arrays, Special Types
       |
       V
  Module 4: Conversion, Scope & Certification
       |
       V
  Data Types Expert 🎉
  

Mini summary: You now understand the basics of variables and data types. Time to go deeper!

Key Vocabulary

WordSimple Definition
VariableA named container for a value.
ValueAny piece of data (number, text, etc.).
Data TypeThe kind of value (number, string, etc.).
letCreates a variable that can change.
constCreates a variable that cannot change.
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.
ObjectA collection of key-value pairs.
ArrayA list of values.
typeofAn operator that tells the type of a value.
ConsoleA tool for testing JavaScript.
camelCaseA naming style like totalSales.

Important Concepts

  • Variables store values: They are named containers.
  • Data types describe values: Number, string, boolean, etc.
  • Use let for changing values: Use const for fixed values.
  • Names should be clear: camelCase is the standard.
  • typeof tells type: Safe way to check data.
  • Console tests code: Your safe playground.
  • Websites use variables: To greet and remember users.
  • Mistakes are common: Read error messages to fix them.
  • Best practices matter: Clean names and correct types.
  • Practice makes perfect: Test variables in the console.

Step-by-step Explanations

How to create a variable step by step

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

How to test a variable in the console step by step

  1. Open the browser console.
  2. Type let name = "Ada";.
  3. Press Enter.
  4. Type name and press Enter.
  5. See "Ada".

How to check a data type step by step

  1. Type typeof "Hello".
  2. Press Enter.
  3. See "string".
  4. Try with numbers and booleans.

How to choose let or const step by step

  1. Ask: Will the value change?
  2. If yes, use let.
  3. If no, use const.
  4. Test in the console.

How to name a variable step by step

  1. Choose a descriptive word.
  2. Combine words in camelCase.
  3. Do not start with a number.
  4. Avoid reserved words.
  5. Keep it readable.

Real-life Examples

  • Banks: Store customer name, balance, and account type.
  • Schools: Store student name, class, and score.
  • Homes: Store chores, shopping lists, and budgets.
  • Shops: Store products, prices, and quantities.
  • Web apps: Store user profiles, posts, and comments.

Nigerian Examples

  • Lagos traders: Store price, quantity, and product name.
  • Abuja banks: Store customer name, balance, and city.
  • Port Harcourt schools: Store student name, score, and class.
  • Onitsha shops: Store product name, price, and stock.
  • Kano fintechs: Store amount, sender, and receiver.

Fun Examples Children Can Relate To

  • Pets: petName = "Buddy".
  • Games: playerScore = 500.
  • Snacks: favouriteSnack = "Chin Chin".
  • Toys: toyCount = 12.
  • Reading: booksRead = 5.

Everyday Examples

  • Shopping: shoppingTotal = 5000.
  • Budget: monthlyBudget = 50000.
  • Time: currentHour = 14.
  • Cooking: numberOfCups = 2.
  • Travel: distanceKm = 120.

Parent Tips

  • Show your child how variables appear in real life (ID cards, forms).
  • Encourage testing in the browser console.
  • Practice with shopping lists or budgets.
  • Explain let and const with simple examples.
  • Praise curiosity and questions.
  • Read about JavaScript together.
  • Keep sessions short.
  • Celebrate small wins.
  • Let them teach you.
  • Support their learning journey.

Interesting Facts

  • JavaScript variables can hold anything.
  • You can change a variable’s type later.
  • typeof null returns "object" — a famous quirk.
  • const does not make objects frozen — only the name is fixed.
  • Variables make websites personalized.
  • Every app uses hundreds of variables.
  • Nigerian developers use variables in every project.
  • JavaScript runs in every modern browser.

Did You Know?

  • Did you know "5" + 5 gives "55" in JavaScript?
  • Did you know you can use let without a value?
  • Did you know you can chain variables, like a = b = 5?
  • Did you know null is a type and a value?
  • Did you know undefined is a type and a value?
  • Did you know JavaScript has a typeof operator?
  • Did you know console.log() prints to the console?
  • Did you know Nigeria has one of Africa’s fastest-growing developer communities?

Remember This

  • Variables are named containers.
  • Data types describe values.
  • let changes; const does not.
  • Names should be clear.
  • typeof tells the type.
  • The console tests code.
  • Websites use variables.
  • Mistakes are common and fixable.
  • Best practices prevent bugs.
  • Practice makes perfect.

Common Mistakes

  • Starting names with a number.
  • Using reserved words as names.
  • Reassigning a const.
  • Mixing data types.
  • Forgetting semicolons.
  • Using undefined values.
  • Not testing in the console.
  • Choosing unclear names.

Best Practices

  • Use const by default.
  • Use let only when needed.
  • Use clear names in camelCase.
  • Use the right data type.
  • Check types with typeof.
  • Test in the browser console.
  • Keep one purpose per variable.
  • Avoid very short or long names.
  • Comment tricky values.
  • Read error messages carefully.

Illustrations and Diagrams

Variable as Labeled Box

  +-----------+
  | name: Ada |
  +-----------+

  +-----------+
  | age: 13   |
  +-----------+
  

let vs const

  let   →  whiteboard (can change)
  const →  stone tablet (cannot change)
  

Common Data Types

  Number:    42, 3.14
  String:    "Hello", "Ada"
  Boolean:   true, false
  Null:      null
  Undefined: undefined
  Object:    { name: "Ada" }
  Array:     [1, 2, 3]
  

typeof Examples

  typeof "Hello"   →  "string"
  typeof 42        →  "number"
  typeof true      →  "boolean"
  

Your Learning Journey

  Module 1: Foundations
       |
       V
  Module 2: Strings, Numbers, Booleans
       |
       V
  Module 3: Objects, Arrays, Special Types
       |
       V
  Module 4: Conversion, Scope & Certification
       |
       V
  Data Types Expert 🎉
  

Comparison Tables

let vs const

Featureletconst
Can change?YesNo
Best forChanging valuesFixed values
Examplelet score = 90const pi = 3.14

Common Data Types

TypeExample
Number42, 3.14
String"Ada", "Hello"
Booleantrue, false
Nullnull
Undefinedundefined
Object{ name: "Ada" }
Array[1, 2, 3]

Good vs Bad Names

GoodBad
customerNamecn
totalSalests
priceOfRicep
monthlyBudgetmb

typeof Results

Valuetypeof
"hi"string
5number
trueboolean
undefinedundefined
nullobject

Lesson Summaries

Lesson 1: A variable is a named container for a value.

Lesson 2: Variables save time and keep information organized.

Lesson 3: Create variables with let or const.

Lesson 4: let changes; const does not.

Lesson 5: Use clear names in camelCase.

Lesson 6: Data types describe what kind of value is inside.

Lesson 7: Numbers are for math and counting.

Lesson 8: Strings are text inside quotes.

Lesson 9: Booleans are true or false.

Lesson 10: Other types: null, undefined, object, array.

Lesson 11: typeof tells the type of a value.

Lesson 12: The console is your testing ground.

Lesson 13: Websites use variables to greet and remember users.

Lesson 14: Common mistakes: bad names, mixing types.

Lesson 15: Best practices: const by default, clear names.

Lesson 16: You now understand the basics of variables and data types.

End-of-Module Summary

Congratulations! You have finished Module One of the Variables & Data Types for Web course. You learned what a variable is, why variables matter, and how to create them. You learned about let and const, naming rules, and common data types. You learned how to use typeof to check types and how to test code in the browser console. You learned how real websites use variables. You learned common mistakes and best practices. Most importantly, you now understand the foundation of every JavaScript program. In the next module, you will learn about strings, numbers, and booleans in depth.

Frequently Asked Questions

  1. What is a variable? A named container for a value.
  2. What is a data type? The kind of value a variable holds.
  3. What is the difference between let and const? let can change; const cannot.
  4. How do I name a variable? Use clear names in camelCase.
  5. What is typeof? An operator that tells the type of a value.
  6. How do I open the console? Press Ctrl + Shift + J (Windows) or Cmd + Option + J (Mac).
  7. What is a string? Text inside quotes.
  8. What is a number? A numeric value like 5 or 3.14.
  9. What is a boolean? A true or false value.
  10. Why do variables matter? They let websites remember and reuse information.

Matching Exercises

Match the term to its meaning.

TermMeaning
1. VariableA. The kind of value
2. Data typeB. A named container for a value
3. letC. Tells the type of a value
4. constD. A variable that can change
5. typeofE. A variable that cannot change

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

Scenario-based Exercises

  1. Scenario: You want to store a name.
    Answer: Use a string variable.
  2. Scenario: You want to store an age.
    Answer: Use a number variable.
  3. Scenario: You want to store if a customer paid.
    Answer: Use a boolean variable.
  4. Scenario: You want to check a value’s type.
    Answer: Use typeof.
  5. Scenario: You want a value that never changes.
    Answer: Use const.

Group Activity

Title: “Create a Class Register Together”

Instructions: In groups of 3–4, create 5 variables for a class register: studentName, studentAge, studentClass, hasPaidFees, and favouriteSubject. Print them using console.log. Present to the class.

Goal: Practice variables and data types.

Individual Activity

Task: In the browser console, create:

  • One string variable.
  • One number variable.
  • One boolean variable.
  • One const variable.
  • Use typeof on each.

Write down each and its result.

Mini Project

Project: “My First JavaScript Profile”

Create a small script with variables that describe you:

  • Your name (string).
  • Your age (number).
  • Your city (string).
  • Whether you like coding (boolean).
  • Your favourite food (string).

Print each using console.log() with template literals.

Example:

  let name = "Ada";
  let age = 13;
  let city = "Lagos";
  let likesCoding = true;
  let favouriteFood = "Jollof rice";

  console.log(`My name is ${name}.`);
  console.log(`I am ${age} years old and I live in ${city}.`);
  console.log(`I like coding: ${likesCoding}.`);
  console.log(`My favourite food is ${favouriteFood}.`);
  

Practical Assignment

Assignment: Ask a family member about a small business. Then write JavaScript that:

  1. Stores the business name, owner, product, and price.
  2. Uses the right data type for each.
  3. Prints each variable in a message.
  4. Uses typeof to check at least one type.

Submit: Your code and a short explanation.

Key Takeaways

  • Variables are named containers.
  • Data types describe values.
  • let changes; const does not.
  • Names should be clear.
  • typeof tells the type.
  • The console tests code.
  • Websites use variables.
  • Mistakes are common and fixable.
  • Best practices prevent bugs.
  • Practice makes perfect.

Classroom Discussion Questions

  1. What is a variable, and why is it useful?
  2. What is a data type, and why does it matter?
  3. Why is const sometimes better than let?
  4. Why should variable names be clear?
  5. How does typeof help you write safer code?
  6. What is the browser console used for?
  7. How do websites use variables to remember users?
  8. What mistakes do beginners make with variables?
  9. What is the best practice for naming variables?
  10. What did Ada learn from filling her school form?

Preparation for Module Two

In Module Two, we will learn about strings, numbers, and booleans in depth. We will cover:

  • String methods and concatenation.
  • Number methods and Math.
  • Booleans in real logic.
  • Template literals.
  • Type checking with typeof.
  • Common mistakes and best practices.

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

See you in Module Two!


End of Module One – Variables & Data Types for Web

3

Module Two

Variables & Data Types for Web – Module Two

Module Two: Strings, Numbers and Booleans – The Three Everyday Data Types

“Variables & Data Types for Web” – Learn how JavaScript remembers information

Module Introduction

Welcome back, young web coder! In Module One, you learned what variables and data types are. You learned how to create variables with let and const. You also learned how to check a value’s type with typeof.

Now it is time to go deeper into the three most common data types on the web: strings (text), numbers, and booleans (true/false). These three types appear in almost every website you have ever used. A login page uses strings. A shop page uses numbers. A settings page uses booleans.

In this module, we will learn how to work with each of them, how to use their built-in tools, and how to avoid mistakes. By the end, you will be able to build a simple text-and-number based web calculator and much more.

Let’s begin!

Learning Objectives

After finishing this module, you will be able to:

  • Explain what a string is and how to use it.
  • Use string methods like length, toUpperCase, and slice.
  • Join strings with the + operator and template literals.
  • Explain what a number is and how to use it.
  • Use number methods like toFixed and parseInt.
  • Use the Math object for rounding and randomness.
  • Explain what a boolean is and how to use it.
  • Use booleans in simple decisions.
  • Convert between strings, numbers, and booleans.
  • Complete a mini project and practical assignment.

Warm-up Story: Chidi’s Football Stats Page

Chidi is 14 years old and lives in Abuja. He loves football and wants to build a small web page that shows his favourite team’s statistics. The page would show the team name, the number of goals, and whether the team won its last match.

He opened the browser console and created three variables:

let teamName = "Super Eagles";
let goalsScored = 3;
let didWin = true;
  

Chidi explained:

  • teamName is a string — text inside quotes.
  • goalsScored is a number — a value used for counting.
  • didWin is a boolean — either true or false.

Next, he wanted to show the team name in uppercase. He typed:

teamName.toUpperCase();  // "SUPER EAGLES"
  

He wanted to round a decimal goal average. He typed:

let average = 2.6667;
average.toFixed(2);  // "2.67"
  

He wanted to show a random number. He typed:

Math.floor(Math.random() * 10);  // random number 0–9
  

Finally, he used a boolean in a decision:

if (didWin) {
  console.log("Well done, " + teamName + "!");
} else {
  console.log("Better luck next time.");
}
  

Chidi smiled. Strings, numbers, and booleans had made his page come alive.

Moral of the story: Strings, numbers, and booleans are the everyday building blocks of web pages. Each has its own tools, and each behaves in its own way.

Main Lessons

Lesson 1: What is a String?

Definition: A string is a piece of text inside quotes.

Why it is important: Text is everywhere on the web — names, messages, titles, and labels.

Simple explanation: A string is any text wrapped in quotes.

Real-life example: A bank stores customer names as strings.

School example: A teacher stores student names as strings.

Home example: A family stores addresses as strings.

Nigerian example: A trader stores product names as strings.

Illustration:

  let name    = "Ada";
  let city    = 'Lagos';
  let message = "Welcome!";

  typeof name    →  "string"
  

Mini summary: Strings are text inside quotes, either single or double.

Lesson 2: Creating and Combining Strings

Definition: Combining strings means joining two or more strings together.

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

Simple explanation: The + operator glues strings together.

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

School example: A teacher greets: "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"
  "5" + 5               →  "55"   (careful!)
  

Mini summary: The + operator joins strings together. Watch out for mixing with numbers.

Lesson 3: Template Literals

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 4: Useful String Methods

Definition: String methods are built-in tools that work on strings.

Why it is important: They let you change, check, and slice text easily.

Simple explanation: Methods are like tools that do things to your text.

Real-life example: A bank uppercases account numbers.

School example: A teacher finds the length of a student’s name.

Home example: A family trims extra spaces in a shopping item.

Nigerian example: A trader converts a product name to uppercase for invoices.

Illustration:

  let name = "Ada";

  name.length          →  3
  name.toUpperCase()   →  "ADA"
  name.toLowerCase()   →  "ada"
  name.charAt(0)       →  "A"
  name.slice(0, 2)     →  "Ad"
  name.includes("d")   →  true
  "  Ada  ".trim()     →  "Ada"
  

Mini summary: String methods help you change, check, and slice text.

Lesson 5: What is a Number?

Definition: A number is a numeric value used for math and counting.

Why it is important: Numbers are used for scores, prices, ages, and more.

Simple explanation: Numbers can be whole or decimal.

Real-life example: A bank uses numbers for balances.

School example: A teacher uses numbers for scores.

Home example: A family uses numbers for prices.

Nigerian example: A trader uses numbers for quantities and prices.

Illustration:

  let age    = 13;         // whole number
  let price  = 3000.50;    // decimal
  let score  = 90;

  typeof age     →  "number"
  

Mini summary: Numbers are used for math and values like age, price, and score.

Lesson 6: Doing Math with Numbers

Definition: Math with numbers uses operators like +, -, *, /.

Why it is important: Websites constantly calculate totals, averages, and more.

Simple explanation: It is the same math you do in school, but the computer does it instantly.

Real-life example: A bank calculates interest with balance * 0.05.

School example: A teacher averages scores with (a + b + c) / 3.

Home example: A family doubles a recipe with cups * 2.

Nigerian example: A trader calculates total with price * quantity.

Illustration:

  5 + 3     →  8
  10 - 4    →  6
  3 * 4     →  12
  12 / 3    →  4
  2 ** 3    →  8
  10 % 3    →  1
  

Mini summary: Numbers are used with math operators to calculate values.

Lesson 7: Useful Number Methods

Definition: Number methods are built-in tools that work on numbers.

Why it is important: They let you round, format, and convert numbers.

Simple explanation: Methods are like tools that help you work with numbers.

Real-life example: A bank formats money to two decimal places.

School example: A teacher rounds scores to whole numbers.

Home example: A family converts a text price into a real number.

Nigerian example: A trader formats prices with commas.

Illustration:

  let price = 3000.5678;

  price.toFixed(2)          →  "3000.57"
  parseInt("3000")          →  3000
  parseFloat("3000.50")     →  3000.5
  Number("500")             →  500
  

Mini summary: Number methods help you format and convert numbers.

Lesson 8: The Math Object

Definition: The Math object gives you useful math tools.

Why it is important: You need to round, get random numbers, and find the biggest value.

Simple explanation: Math is a toolbox of math helpers.

Real-life example: A bank rounds interest to the nearest naira.

School example: A teacher finds the highest score in a class.

Home example: A family finds the lowest price in a shop.

Nigerian example: A trader picks a random winner for a raffle.

Illustration:

  Math.round(4.6)     →  5
  Math.floor(4.9)     →  4
  Math.ceil(4.1)      →  5
  Math.max(3, 7, 2)   →  7
  Math.min(3, 7, 2)   →  2
  Math.random()       →  0.0 – 0.9999
  

Mini summary: The Math object gives you tools to round, find min/max, and get random numbers.

Lesson 9: What is a Boolean?

Definition: A boolean is a value that is either true or false.

Why it is important: Booleans control decisions on websites.

Simple explanation: A boolean answers yes/no questions.

Real-life example: A bank checks if a customer has paid fees (true/false).

School example: A teacher checks if a student is present (true/false).

Home example: A family checks if the door is locked (true/false).

Nigerian example: A trader checks if a product is in stock (true/false).

Illustration:

  let hasPaidFees = true;
  let isOpen      = false;

  typeof hasPaidFees  →  "boolean"
  

Mini summary: Booleans are true or false values used for decisions.

Lesson 10: Booleans in Real Decisions

Definition: Booleans are used in conditions, like if statements.

Why it is important: Every website decision uses a boolean.

Simple explanation: When a boolean is true, one thing happens. When false, another thing happens.

Real-life example: A bank shows "Welcome" if isLoggedIn is true.

School example: A teacher marks "Present" if isHere is true.

Home example: A family locks the door if isNight is true.

Nigerian example: A trader sells if inStock is true.

Illustration:

  let isOpen = true;

  if (isOpen) {
    console.log("Welcome in!");
  } else {
    console.log("Sorry, we are closed.");
  }
  

Mini summary: Booleans are used to make decisions in code.

Lesson 11: Converting Between Types

Definition: Converting means changing a value from one type to another.

Why it is important: Sometimes a number comes as text, and you need to convert it.

Simple explanation: It is like changing naira to dollars — same value, different form.

Real-life example: A bank converts a typed PIN (string) to a number.

School example: A teacher converts a score from text to number.

Home example: A family converts a typed price to a number before adding.

Nigerian example: A trader converts a WhatsApp price to a number.

Illustration:

  Number("500")         →  500
  String(500)           →  "500"
  Boolean(1)            →  true
  parseInt("500")       →  500
  parseFloat("50.5")    →  50.5
  

Mini summary: Use Number(), String(), and Boolean() to convert values between types.

Lesson 12: Checking Types with typeof

Definition: typeof tells you the type of a value.

Why it is important: It helps you avoid bugs by checking 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 adding interest.

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

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 undefined →  "undefined"
  typeof null      →  "object"
  

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

Lesson 13: Common Mistakes with the Three Types

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

Why it is important: Mixing types gives wrong results.

Simple explanation: Like adding milk to a shoe — the wrong tool for the job.

Real-life example: A bank adds "500" to 1000 and gets "5001000".

School example: A teacher adds "90" and 10 and gets "9010".

Home example: A family adds "5" eggs and 3 eggs and gets "53".

Nigerian example: A trader adds "3000" and 500 and charges the wrong amount.

Table of common mistakes:

MistakeWhat HappensHow to Fix
Mixing strings and numbersWrong resultConvert with Number()
Using quotes on numbersText instead of numberRemove quotes
Forgetting to convert inputWrong mathUse parseInt/parseFloat
Comparing string "5" to number 5Wrong equalityUse === or convert
Using booleans in mathUnexpected numbersKeep booleans for logic
Assuming text is a numberNaN errorsCheck with typeof

Mini summary: Common mistakes: mixing types, forgetting to convert, and using quotes on numbers.

Lesson 14: Best Practices for Strings, Numbers, Booleans

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

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

Simple explanation: Like keeping your tools sharp and organized.

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

School example: A student writes neat, readable code.

Home example: A family keeps a tidy shopping list.

Nigerian example: A business writes clear, easy-to-maintain code.

List of best practices:

  • Use template literals for strings.
  • Convert text numbers to real numbers before math.
  • Use === instead of ==.
  • Use toFixed when showing money.
  • Use Math.round when displaying whole numbers.
  • Use booleans for yes/no logic.
  • Check types with typeof.
  • Test in the console.
  • Add comments for tricky values.
  • Keep code readable.

Mini summary: Best practices: template literals, type conversion, and clean code.

Lesson 15: Putting It All Together – Your Type Toolkit

You now know how to work with strings, numbers, and booleans.

What you learned:

  • Strings, how to join them, and string methods
  • Template literals
  • Numbers, math, and number methods
  • The Math object
  • Booleans and how to use them in decisions
  • Type conversion
  • typeof and common mistakes
  • Best practices

Next steps: In Module Three, you will learn about objects, arrays, and special types.

Illustration:

  Your Learning Journey:

  Module 1: Foundations
       |
       V
  Module 2: Strings, Numbers, Booleans
       |
       V
  Module 3: Objects, Arrays, Special Types
       |
       V
  Module 4: Conversion, Scope & Certification
       |
       V
  Data Types Expert 🎉
  

Mini summary: You now have a full toolkit for the three everyday data types.

Key Vocabulary

WordSimple Definition
StringText inside quotes.
NumberA numeric value like 5 or 3.14.
BooleanA true or false value.
Template literalA string using backticks and ${ }.
MethodA built-in tool that works on a value.
ConcatenationJoining strings with +.
parseIntConverts a string to a whole number.
parseFloatConverts a string to a decimal number.
toFixedRounds a number to a set number of decimals.
MathA built-in object of math helpers.
typeofAn operator that tells the type of a value.
NaN"Not a Number" — an invalid number value.
Type conversionChanging a value from one type to another.
camelCaseA naming style like totalSales.
ConsoleA tool for testing JavaScript.

Important Concepts

  • Strings are text: Inside quotes.
  • + joins strings: Concatenation.
  • Template literals are cleaner: Backticks and ${ }.
  • String methods do things: length, toUpperCase, slice, trim.
  • Numbers are for math: Whole and decimal.
  • Number methods format values: toFixed, parseInt, parseFloat.
  • Math helps you round and random: Math.round, Math.random.
  • Booleans are true or false: For decisions.
  • Convert types when needed: Number(), String(), Boolean().
  • typeof checks types: Always be safe.

Step-by-step Explanations

How to create and use a string step by step

  1. Write let name = "Ada";.
  2. Print it with console.log(name).
  3. Try name.toUpperCase().
  4. Try name.length.

How to use a template literal step by step

  1. Write a backtick `.
  2. Type your message with ${value} inside.
  3. Close with another backtick.
  4. Print it in the console.

How to do math with numbers step by step

  1. Create two variables: let a = 10; and let b = 5;.
  2. Try a + b, a * b, etc.
  3. Print the results.

How to format a number step by step

  1. Type let price = 3000.5678;.
  2. Type price.toFixed(2).
  3. Press Enter and see "3000.57".

How to use a boolean step by step

  1. Type let isOpen = true;.
  2. Write an if-statement using isOpen.
  3. Test with false to see the other result.

Real-life Examples

  • Banks: Format money with toFixed(2).
  • Schools: Average scores with numbers.
  • Homes: Track chores with booleans.
  • Shops: Display product names as strings.
  • Web apps: Show greetings with template literals.

Nigerian Examples

  • Lagos traders: Format prices as ₦3,000.00.
  • Abuja banks: Round interest with Math.round.
  • Port Harcourt schools: Average scores with numbers.
  • Onitsha shops: Use booleans for inStock.
  • Kano fintechs: Convert typed amounts to numbers.

Fun Examples Children Can Relate To

  • Pets: petName.toUpperCase().
  • Games: Math.random() for random dice.
  • Snacks: Format the price with toFixed(2).
  • Toys: Use a boolean for "isFavourite".
  • Reading: Count pages with numbers.

Everyday Examples

  • Shopping: Format totals with toFixed(2).
  • Budget: Track "isOverBudget" as a boolean.
  • Time: Convert text hours to numbers.
  • Cooking: Use template literals for recipes.
  • Travel: Round distances with Math.round.

Parent Tips

  • Show how strings appear in real life (names, messages).
  • Practice numbers with shopping or budgets.
  • Explain booleans as "yes/no" or "on/off".
  • Encourage testing in the console.
  • Practice template literals together.
  • Praise curiosity and questions.
  • Keep sessions short.
  • Celebrate small wins.
  • Let them teach you.
  • Support their learning journey.

Interesting Facts

  • Strings can be very long — even whole books.
  • Numbers in JavaScript can be positive or negative.
  • Math.random() never returns exactly 1.
  • Booleans are named after George Boole.
  • toFixed returns a string, not a number.
  • parseInt stops at the first non-number.
  • Template literals can span many lines.
  • Nigerian developers use these types daily.

Did You Know?

  • Did you know "5" + 5 gives "55"?
  • Did you know "5" - 5 gives 0?
  • Did you know Boolean(0) is false?
  • Did you know Boolean("") is false?
  • Did you know Math.max(1, 2, 3) is 3?
  • Did you know strings have a length property?
  • Did you know NaN means "Not a Number"?
  • Did you know typeof NaN is "number"?

Remember This

  • Strings are text inside quotes.
  • + joins strings together.
  • Template literals use backticks.
  • Numbers are for math.
  • toFixed formats money.
  • Math helps with rounding and random.
  • Booleans are true or false.
  • Convert types when needed.
  • typeof checks types.
  • Test in the console.

Common Mistakes

  • Mixing strings and numbers.
  • Using quotes on numbers.
  • Forgetting to convert input.
  • Comparing "5" with 5 using ===.
  • Using booleans in math.
  • Assuming text is a number.
  • Not testing in the console.
  • Using == instead of ===.

Best Practices

  • Use template literals for strings.
  • Convert text numbers to real numbers.
  • Use === instead of ==.
  • Use toFixed for money.
  • Use Math.round for whole numbers.
  • Use booleans for yes/no logic.
  • Check types with typeof.
  • Test in the console.
  • Comment tricky values.
  • Keep code readable.

Illustrations and Diagrams

The Three Everyday Types

  String:   "Ada"          → text
  Number:   42, 3.14       → math
  Boolean:  true, false    → decisions
  

String Concatenation

  "Hello, " + "Ada"  →  "Hello, Ada"
  

Template Literal

  `Hello, ${name}!`
  

Math Rounding

  Math.round(4.6)  →  5
  Math.floor(4.9)  →  4
  Math.ceil(4.1)   →  5
  

Your Learning Journey

  Module 1: Foundations
       |
       V
  Module 2: Strings, Numbers, Booleans
       |
       V
  Module 3: Objects, Arrays, Special Types
       |
       V
  Module 4: Conversion, Scope & Certification
       |
       V
  Data Types Expert 🎉
  

Comparison Tables

String vs Number

FeatureStringNumber
Example"Ada"42
QuotesYesNo
MathNoYes
LengthYesNo

Number vs Boolean

FeatureNumberBoolean
ValuesAny numbertrue or false
UseMathDecisions
Example42true

String Methods

MethodWhat it does
lengthCounts characters
toUpperCase()Makes all caps
toLowerCase()Makes all small
slice()Cut a piece
includes()Check for text
trim()Remove extra spaces

Type Conversion

ConversionExampleResult
String → NumberNumber("500")500
Number → StringString(500)"500"
Any → BooleanBoolean(1)true
Text → IntegerparseInt("500")500
Text → DecimalparseFloat("50.5")50.5

Lesson Summaries

Lesson 1: Strings are text inside quotes.

Lesson 2: + joins strings together.

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

Lesson 4: String methods change, check, and slice text.

Lesson 5: Numbers are used for math and counting.

Lesson 6: Math operators calculate values.

Lesson 7: Number methods format and convert numbers.

Lesson 8: The Math object gives rounding, min/max, and random.

Lesson 9: Booleans are true or false.

Lesson 10: Booleans are used in decisions.

Lesson 11: Convert types with Number(), String(), Boolean().

Lesson 12: typeof tells the type of a value.

Lesson 13: Common mistakes: mixing types, missing conversion.

Lesson 14: Best practices: template literals, conversion, clean code.

Lesson 15: You now have a full toolkit for the three everyday data types.

End-of-Module Summary

Congratulations! You have finished Module Two of the Variables & Data Types for Web course. You learned how to use strings, numbers, and booleans. You learned how to join strings with + and template literals. You learned string methods like length, toUpperCase, and slice. You learned how to do math with numbers and use number methods like toFixed, parseInt, and parseFloat. You learned about the Math object for rounding and random numbers. You learned about booleans and how to use them in decisions. You learned how to convert between types and check types with typeof. You learned common mistakes and best practices. Most importantly, you can now work confidently with the three most common data types on the web. In the next module, you will learn about objects, arrays, and special types.

Frequently Asked Questions

  1. What is a string? Text inside quotes.
  2. How do I join strings? Use + or template literals.
  3. What is a template literal? A string using backticks and ${ }.
  4. What is a number? A numeric value like 5 or 3.14.
  5. How do I format money? Use toFixed(2).
  6. What does Math.random() do? Gives a random number between 0 and 1.
  7. What is a boolean? A true or false value.
  8. How do I convert text to a number? Use Number() or parseInt().
  9. What does typeof do? Tells the type of a value.
  10. What is NaN? "Not a Number" — an invalid number value.

Matching Exercises

Match the term to its meaning.

TermMeaning
1. StringA. A true or false value
2. NumberB. Text inside quotes
3. BooleanC. A built-in math tool
4. MathD. A numeric value
5. typeofE. Tells the type of a value

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

Scenario-based Exercises

  1. Scenario: You want to greet the user by name.
    Answer: Use template literals.
  2. Scenario: You want to round a price to 2 decimals.
    Answer: Use toFixed(2).
  3. Scenario: You want a random number 1–6 for a dice.
    Answer: Use Math.floor(Math.random() * 6) + 1.
  4. Scenario: You want a yes/no decision.
    Answer: Use a boolean.
  5. Scenario: You have "500" as text and want to add it.
    Answer: Use Number("500") or parseInt("500").

Group Activity

Title: “Build a Small Bill Calculator Together”

Instructions: In groups of 3–4, create variables for two items (name, price, quantity). Calculate the total using numbers. Format the total with toFixed(2). Show a friendly message with template literals. Present to the class.

Goal: Practice strings, numbers, and template literals.

Individual Activity

Task: In the browser console, create:

  • One string variable.
  • One number variable.
  • One boolean variable.
  • Join two strings.
  • Round a number with Math.round.
  • Use typeof on each.

Write down each and its result.

Mini Project

Project: “My First Shop Receipt”

Create a JavaScript receipt with:

  • Shop name (string).
  • Two products with names (string) and prices (number).
  • Quantities (number).
  • Subtotal for each product.
  • Total using numbers.
  • A boolean for "discountApplied".
  • Final message using template literals and toFixed(2).

Example:

  let shopName = "Sweet Lagos Bakery";
  let item1 = "Cake",  price1 = 5000, qty1 = 2;
  let item2 = "Bread", price2 = 1000, qty2 = 3;
  let discountApplied = true;

  let total = (price1 * qty1) + (price2 * qty2);
  if (discountApplied) total -= 500;

  console.log(`${shopName} — Total: ₦${total.toFixed(2)}`);
  

Practical Assignment

Assignment: Ask a family member about a small business. Then write JavaScript that:

  1. Stores a product name (string) and price (number).
  2. Stores a boolean for "inStock".
  3. Calculates the total for a chosen quantity.
  4. Formats the price with toFixed(2).
  5. Prints a message using template literals.

Submit: Your code and a short explanation.

Key Takeaways

  • Strings are text inside quotes.
  • + joins strings together.
  • Template literals use backticks.
  • Numbers are for math.
  • toFixed formats money.
  • Math helps with rounding and random.
  • Booleans are true or false.
  • Convert types when needed.
  • typeof checks types.
  • Test in the console.

Classroom Discussion Questions

  1. What is the difference between a string and a number?
  2. Why do we use template literals?
  3. What does toFixed(2) do?
  4. How is Math.random() useful?
  5. When would you use a boolean?
  6. What happens when you mix strings and numbers?
  7. How do you convert text to a number?
  8. Why is typeof useful?
  9. What mistakes do beginners make with these types?
  10. What did Chidi learn from building his football stats page?

Preparation for Module Three

In Module Three, we will learn about objects, arrays, and special types. We will cover:

  • Objects and key-value pairs.
  • Arrays and indexes.
  • Array methods like push, pop, unshift, shift.
  • Looping through arrays.
  • null and undefined.
  • Nesting objects and arrays.
  • JSON basics.

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

See you in Module Three!


End of Module Two – Variables & Data Types for Web

4

Module Three

Module Three: Variables & Data Types for the Web

📘 Module Three: Variables & Data Types for the Web

Part of the “Web Basics for Young Coders” course — written for curious 10‑ to 13‑year‑olds.

🌟 Module Introduction

Imagine you are building a house. You need different containers to hold things: a bucket for water, a box for nails, a bag for cement. In the world of web pages, we also need containers to hold information. Those containers are called variables. And the kind of information they hold — like numbers, words, or true/false — are called data types.

In this module, you will learn how to create variables, give them names, and store different types of data. You will see how variables make your web pages smart and interactive. You will learn through stories, examples, and fun exercises. By the end, you will be able to write simple JavaScript code that remembers things — just like a human brain remembers your name!

Let’s start this journey together. Take your time. Read each lesson slowly. Try the examples on your computer (or on paper). Ready? Let’s go!

🎯 Learning Objectives

After finishing this module, you will be able to:

  • Explain what a variable is using simple words.
  • Create variables in JavaScript using let, const, and var.
  • Name variables correctly (rules and good habits).
  • Identify and use basic data types: numbers, strings, booleans, undefined, and null.
  • Change the value inside a variable.
  • Combine variables with text (string concatenation).
  • Understand why data types matter in real web pages.
  • Spot and fix common mistakes with variables.
  • Use variables to solve simple problems.
  • Build a tiny mini‑project that uses variables and data types.

📖 Warm-up Story: Ada and the Magic Boxes

Ada lives in Lagos, Nigeria. One day, her grandmother gave her three magic boxes. “Each box can hold only one kind of thing,” Grandma said. “The blue box holds numbers. The red box holds words. The green box holds yes or no answers.”

Ada was excited. She put her age (12) in the blue box. She put her name (“Ada”) in the red box. She put “true” in the green box because she loves jollof rice. Then she realised: if she wanted to change her age next year, she could just put a new number in the blue box. The box keeps the value safe until she needs it.

In web programming, those magic boxes are called variables. The kinds of things they hold are data types. Just like Ada’s boxes, variables help your web page remember information — your name, your score, whether you clicked a button, and much more. Are you ready to open your own magic boxes? Let’s dive in!

📚 Lesson 1: What is a Variable?

Definition

A variable is a named container that stores a value. You can think of it as a labelled box where you keep information.

Why it is important

Without variables, your web page would forget everything. Variables let you save data, change it, and use it again.

Simple explanation

Imagine you have a box with the word “score” written on it. You put the number 10 inside. Later, you can open the box, take out 10, add 5, and put back 15. The box always has a label (the variable name) and something inside (the value).

Real-life example

Your school bag is a variable. Its name is “schoolBag”. Inside you put your books (values). Tomorrow you might put different books — the bag stays the same, but the contents change.

School example

In a classroom, the teacher writes “Today’s date” on the board. That’s like a variable called todayDate. Each day she erases it and writes a new date.

Home example

Your phone’s battery percentage is a variable called batteryLevel. It changes from 100 to 99 to 98…

Nigerian example

In a football match, the scoreboard shows “Super Eagles 2 – 1 Ghana”. The score is stored in variables like eaglesScore and ghanaScore. When a goal is scored, the variable changes.

Illustration

   +-------------------+
   |   variable name   |
   |     "score"       |
   +-------------------+
   |   value:  10      |
   +-------------------+
          |
          V
   Later, value becomes 15
    

Mini summary

A variable is a labelled container that holds a value. You can change the value whenever you want.

📚 Lesson 2: How to Create a Variable in JavaScript

Definition

Creating a variable means declaring it and giving it a name. In JavaScript we use keywords like let, const, or var.

Why it is important

You must tell the computer that you want a new container. The keyword is like saying “Hey computer, I’m making a new box!”

Simple explanation

Use let when the value can change. Use const when the value must never change. Use var in older code (we prefer let and const now).

Real-life example

let is like a whiteboard — you can erase and write again. const is like a carved stone — once written, it stays.

School example

Your class teacher writes the number of students present on a whiteboard (let). The school’s name on the gate is carved in stone (const).

Home example

The TV volume (let volume = 10) can change. Your date of birth (const birthday = "12 May 2012") never changes.

Nigerian example

let fuelPrice = 600 (price changes often). const country = "Nigeria" (never changes).

Illustration

   let score = 0;          // can change
   const PI = 3.14;        // cannot change
   var oldStyle = "ok";    // older way
    

Mini summary

Use let for values that change, const for values that stay the same, and avoid var unless you see it in old code.

📚 Lesson 3: Naming Your Variables

Definition

Variable names are the labels you give to your boxes. They must follow certain rules.

Why it is important

Good names make your code easy to read. Bad names confuse you and others.

Simple explanation

  • Names can contain letters, numbers, $, and _.
  • They cannot start with a number.
  • They cannot be words like let, const, if (reserved words).
  • They are case‑sensitive: score and Score are different.

Real-life example

Naming a dog “Dog” is confusing. Naming it “Bingo” is better. So name your variable playerScore not s.

School example

Instead of calling your notebook “book1”, call it “MathsNotes”.

Home example

Label your kitchen jars “Rice”, “Beans”, “Sugar” — not “Jar1”, “Jar2”.

Nigerian example

Call your variable jollofRicePortions not jrp. Clear names help everyone.

Illustration

   ✅ let playerScore = 100;
   ❌ let 2players = 5;     // cannot start with number
   ❌ let my-name = "Ada";  // hyphen not allowed
   ✅ let my_name = "Ada";  // underscore is fine
    

Mini summary

Use clear, descriptive names. Start with a letter, $, or _. No spaces or hyphens.

📚 Lesson 4: Data Type – Numbers

Definition

A number data type stores numeric values, like 7, 3.14, or -5.

Why it is important

Numbers are used for scores, prices, ages, calculations, and much more.

Simple explanation

You can do math with numbers: add (+), subtract (-), multiply (*), divide (/).

Real-life example

The price of a loaf of bread is a number. Your age is a number.

School example

Your test score is a number. The number of pencils in your bag is a number.

Home example

The temperature in the fridge is a number. The number of eggs left is a number.

Nigerian example

The naira price of a bus ticket (e.g., 500) is a number. The number of goals scored by the Super Eagles is a number.

Illustration

   let age = 12;
   let price = 350.50;
   let temperature = -3;
    

Mini summary

Numbers are for counting, measuring, and calculating. No quotes around them.

📚 Lesson 5: Data Type – Strings

Definition

A string is a sequence of characters (letters, numbers, symbols) wrapped in quotes. It represents text.

Why it is important

Strings hold names, sentences, addresses, and any written information.

Simple explanation

Use single quotes ' ', double quotes " ", or backticks ` ` to make a string.

Real-life example

Your name is a string. Your school’s name is a string.

School example

The title of a book is a string. The answer to “What is your favourite subject?” is a string.

Home example

A text message you send is a string. Your address is a string.

Nigerian example

"Lagos", "Jollof rice", "Nollywood" are all strings.

Illustration

   let name = "Ada";
   let city = 'Abuja';
   let greeting = `Hello, welcome!`;
    

Mini summary

Strings are text inside quotes. They can be empty ("") or long.

📚 Lesson 6: Data Type – Booleans

Definition

A boolean has only two possible values: true or false.

Why it is important

Booleans help your program make decisions. For example, “Is the user logged in?” true or false.

Simple explanation

Think of a light switch: it is either ON (true) or OFF (false).

Real-life example

“Is it raining?” — true or false. “Do I have money?” — true or false.

School example

“Did I finish my homework?” — true or false.

Home example

“Is the door locked?” — true or false.

Nigerian example

“Is there fuel in the generator?” — true or false. “Did Nigeria win the match?” — true or false.

Illustration

   let isRaining = true;
   let hasMoney = false;
    

Mini summary

Booleans are yes/no answers written as true or false (no quotes).

📚 Lesson 7: Data Type – Undefined and Null

Definition

undefined means a variable has been declared but has no value yet. null means “no value” on purpose.

Why it is important

They help you know when something is missing or empty.

Simple explanation

Imagine a box with no label (undefined) versus a box with a label but deliberately empty (null).

Real-life example

Your friend’s phone number is undefined if you never saved it. Your lunch box is null if you decided to fast today.

School example

A test score is undefined if you were absent. A homework mark is null if the teacher chose not to grade it.

Home example

The TV remote battery level is undefined if the remote is broken. Your pocket money is null if you spent it all.

Nigerian example

The price of petrol at a closed station is undefined. The number of passengers in an empty bus is null (zero is a number, null is “nothing”).

Illustration

   let score;          // undefined
   let favouriteFood = null;  // intentionally empty
    

Mini summary

undefined happens automatically when you forget to give a value. null is given on purpose to mean “nothing”.

📚 Lesson 8: Changing the Value of a Variable

Definition

If you used let, you can give the variable a new value later.

Why it is important

Web pages are dynamic — things change. Scores go up, names change, counters increase.

Simple explanation

Just write the variable name again and assign a new value with =.

Real-life example

Your age changes every year. So age = age + 1.

School example

Your class attendance count changes. presentCount = presentCount + 1.

Home example

The number of slices of bread decreases. breadSlices = breadSlices - 1.

Nigerian example

The Super Eagles score increases: eaglesScore = eaglesScore + 1.

Illustration

   let score = 0;
   score = 10;    // now score is 10
   score = score + 5;  // now score is 15
    

Mini summary

Variables declared with let can be updated. const cannot be updated.

📚 Lesson 9: Combining Strings (Concatenation)

Definition

Concatenation means joining strings together using the + operator.

Why it is important

You often need to build messages using variables, like “Hello, Ada!”

Simple explanation

Just use + between strings and variables that hold strings.

Real-life example

Writing a greeting card: “Dear” + “ “ + name + “,”

School example

Making a name tag: “Student: ” + studentName

Home example

Sending a text: “Good morning, ” + mum

Nigerian example

“Welcome to ” + city + “, the centre of excellence!”

Illustration

   let firstName = "Ada";
   let greeting = "Hello, " + firstName + "!";
   // greeting becomes "Hello, Ada!"
    

Mini summary

Use + to join strings. Make sure to include spaces where needed.

📚 Lesson 10: Template Literals (Backticks)

Definition

Template literals let you insert variables inside a string using ${ } and backticks.

Why it is important

They make combining strings easier and cleaner, especially with many variables.

Simple explanation

Instead of lots of +, you write one string with placeholders.

Real-life example

Filling a form: “My name is ${name} and I am ${age} years old.”

School example

“Student ${name} scored ${score} marks.”

Home example

“Dinner is ${food} and it costs ₦${price}.”

Nigerian example

“${player} scored a goal for Nigeria!”

Illustration

   let name = "Ada";
   let age = 12;
   let message = `My name is ${name} and I am ${age} years old.`;
    

Mini summary

Use backticks and ${ } to drop variables right into strings.

📚 Lesson 11: Why Data Types Matter

Definition

Data types tell the computer how to treat a value — as a number, text, true/false, etc.

Why it is important

If you mix types, you can get strange results. For example, "5" + 5 gives "55" (string), not 10.

Simple explanation

Numbers add. Strings join. Booleans help make decisions. Using the wrong type is like putting water in a petrol tank.

Real-life example

If a shop’s price is stored as a string, adding two prices might join them instead of adding them.

School example

If your test scores are strings, averaging them will give a weird result.

Home example

If your shopping list total is a string, you cannot calculate change.

Nigerian example

If bus fares are strings, adding them gives “500300” instead of 800.

Illustration

   let a = 5;        // number
   let b = "5";      // string
   console.log(a + a);  // 10
   console.log(b + b);  // "55"
    

Mini summary

Always use the correct data type for the job. Numbers for math, strings for text.

📚 Lesson 12: Type Checking with typeof

Definition

typeof is an operator that tells you the data type of a value.

Why it is important

It helps you find mistakes when your code behaves strangely.

Simple explanation

Just write typeof variableName and it returns a string like "number" or "string".

Real-life example

Like checking the label on a food packet to see if it’s sugar or salt.

School example

Like checking if an answer is a number or a word before marking it.

Home example

Like checking if the remote control is for the TV or the fan.

Nigerian example

Like checking if a naira note is ₦1000 or ₦500 before using it.

Illustration

   let age = 12;
   console.log(typeof age);  // "number"
   let name = "Ada";
   console.log(typeof name); // "string"
    

Mini summary

typeof is your friend. Use it to check what type a variable holds.

📚 Lesson 13: Converting Between Data Types

Definition

Sometimes you need to change a string to a number, or a number to a string. This is called type conversion.

Why it is important

User input from a web page often comes as strings. You must convert them to numbers for math.

Simple explanation

Use Number() to turn a string into a number. Use String() to turn a number into a string.

Real-life example

When you type your age in a form, it arrives as “12” (string). You convert it to 12 (number) to calculate next year’s age.

School example

If your test score is given as “85” (string), you convert it to 85 to find the average.

Home example

If your shopping list says “3” apples, you convert it to 3 to count them.

Nigerian example

If a bus conductor says “₦500” (string), you convert to 500 to give correct change.

Illustration

   let strNum = "10";
   let num = Number(strNum);   // 10
   let backToStr = String(num); // "10"
    

Mini summary

Use Number() and String() to switch between types when needed.

📚 Lesson 14: Constants and When to Use Them

Definition

A constant is a variable whose value cannot be changed after it is set. In JavaScript we use const.

Why it is important

Some values should never change: your birth date, the value of PI, the name of your country.

Simple explanation

Think of a carved stone tablet. Once written, it stays forever. That’s const.

Real-life example

Your national identity number is a constant. Your school’s name is a constant.

School example

The school’s motto is a constant. The number of days in a week (7) is a constant.

Home example

Your house address is a constant. The number of months in a year (12) is a constant.

Nigerian example

“Nigeria” is a constant. The number of states (36) is a constant.

Illustration

   const BIRTH_YEAR = 2012;
   // BIRTH_YEAR = 2013;  ❌ Error: cannot change
    

Mini summary

Use const for values that must stay the same. It prevents accidental changes.

📚 Lesson 15: Putting It All Together – A Tiny Program

Definition

Now we combine variables and data types to make a small, useful program.

Why it is important

This is how real web pages work — they store data in variables and use it to display messages.

Simple explanation

Let’s write a program that greets a user and calculates their age next year.

Real-life example

A website that says “Welcome, Ada! You will be 13 next year.”

School example

A class register that shows “Student: Ada, Age: 12, Next year: 13”.

Home example

A shopping list that says “3 apples, 2 bread, total 5 items”.

Nigerian example

A football app that shows “Super Eagles scored 2 goals. Next match: Nigeria vs Ghana.”

Illustration

   let userName = "Ada";
   let userAge = 12;
   let nextAge = userAge + 1;
   let message = `Hello ${userName}! Next year you will be ${nextAge}.`;
   console.log(message);
   // Output: Hello Ada! Next year you will be 13.
    

Mini summary

Variables + data types + string concatenation = useful web messages. You just wrote a tiny program!

📖 Key Vocabulary

WordSimple Definition
VariableA named box that holds a value.
Data TypeThe kind of value, like number or text.
NumberA numeric value, like 7 or 3.14.
StringText inside quotes, like "hello".
BooleanTrue or false.
UndefinedA variable with no value yet.
NullAn empty value given on purpose.
DeclarationCreating a variable with let, const, or var.
AssignmentGiving a value to a variable using =.
ConcatenationJoining strings with +.
Template LiteralA string with backticks that can include ${}.
Type ConversionChanging a value from one type to another.
typeofAn operator that tells you the data type.

🔑 Important Concepts

  • Variables store data so your program can remember it.
  • Use let for changeable values, const for fixed values.
  • Data types: number, string, boolean, undefined, null.
  • You can change a let variable but not a const.
  • Strings are text; numbers are for math.
  • Booleans are true/false used for decisions.
  • Use + to join strings, but be careful with numbers and strings.
  • Template literals (` `) make combining strings easier.
  • typeof helps you check data types.
  • Convert types with Number() and String().

🪜 Step-by-Step Explanations

How to create and use a variable

  1. Choose a keyword: let or const.
  2. Pick a clear name (e.g., playerScore).
  3. Use = to assign a value (e.g., let playerScore = 0;).
  4. Use the variable name later to read or change it.
  5. If using let, you can change the value: playerScore = 10;.

How to combine a string and a number

  1. Make sure the number is a number (no quotes).
  2. Make sure the string is in quotes.
  3. Use + to join: "Score: " + 10 gives "Score: 10".
  4. Or use template literal: `Score: ${10}`.

🌍 Real-life Examples

  • Online form: Storing your name (string) and age (number) when you sign up.
  • Game: Keeping track of your score (number) and whether you are still alive (boolean).
  • Weather app: Storing temperature (number) and city name (string).
  • WhatsApp: Storing your contacts’ names (strings) and online status (boolean).
  • Bank app: Storing your balance (number) and account number (string).

🇳🇬 Nigerian Examples

  • Naira and kobo: let price = 1500; (number). let currency = "₦"; (string).
  • Jollof rice: let jollofPortions = 3; (number). let isSpicy = true; (boolean).
  • Lagos traffic: let trafficLevel = "heavy"; (string).
  • Super Eagles: let eaglesScore = 2; let opponentScore = 1; let isWinning = true;.
  • Nollywood: let movieTitle = "The Wedding Party"; let releaseYear = 2016;.

🎈 Fun Examples Children Can Relate To

  • Video game lives: let lives = 3; After losing a life: lives = lives - 1;
  • Pizza slices: let slices = 8; You eat 2: slices = slices - 2;
  • Birthday age: let age = 10; Next year: age = age + 1;
  • Superhero name: let heroName = "Spider-Boy";
  • Do you like chocolate? let likesChocolate = true;

🏠 Everyday Examples

  • Alarm clock: let alarmTime = "7:00 AM"; (string).
  • Phone battery: let batteryPercentage = 85; (number).
  • Light switch: let isLightOn = false; (boolean).
  • Shopping list: let item1 = "Milk"; let item2 = "Bread"; (strings).
  • Number of steps walked: let steps = 3000; (number).

👨‍👩‍👧 Parent Tips

  • Encourage your child to explain variables using everyday objects (boxes, jars, bags).
  • Ask them to name variables clearly — it builds good coding habits.
  • Let them practise with simple examples like storing their age and calculating next year’s age.
  • Remind them that mistakes are normal. undefined and null are not errors; they are tools.
  • Celebrate small wins — like writing their first variable and printing a message.

💡 Interesting Facts

  • The word “variable” comes from “vary”, meaning to change.
  • In the 1950s, programmers used punched cards to store data — no variables like we have today!
  • JavaScript was created in just 10 days in 1995.
  • Some programming languages require you to say the data type before the variable name (e.g., int score = 0;). JavaScript is more relaxed.
  • The typeof operator is so useful that it exists in almost every programming language.

🤔 Did You Know?

  • typeof null returns "object" — a famous bug in JavaScript that was never fixed to avoid breaking old websites.
  • You can use emojis in variable names? Actually, no — JavaScript variable names must use letters, digits, $, or _.
  • The longest variable name can be thousands of characters long, but nobody does that!
  • Strings can contain numbers, like "123", but they are still text.

🧠 Remember This

  • Variables are named containers for data.
  • let for change, const for no change.
  • Numbers, strings, booleans, undefined, null.
  • Use quotes for strings. No quotes for numbers or booleans.
  • Combine strings with + or template literals.
  • Check types with typeof.
  • Convert types with Number() and String().
  • Clear names make happy coders!

❌ Common Mistakes

MistakeWhy it’s wrongFix
let 2cool = "yes";Variable names cannot start with a number.let cool2 = "yes";
let my-name = "Ada";Hyphens are not allowed.let my_name = "Ada";
const age = 12; age = 13;Cannot reassign a constant.Use let if it changes.
let score = "10"; let total = score + 5;Results in "105" (string) not 15.Use Number(score) + 5.
let name = Ada;Missing quotes — Ada is seen as a variable, not text.let name = "Ada";

✅ Best Practices

  • Use const by default, and let only when you need to change the value.
  • Give meaningful names: playerScore not x.
  • Use camelCase for multi-word names: myFavoriteFood.
  • Always end statements with a semicolon ;.
  • Use template literals for building messages.
  • Check your data types with typeof when debugging.

📊 ASCII Illustrations, Diagrams & Flowcharts

Variable as a labelled box

   +---------------------+
   |   name: "score"     |
   +---------------------+
   |   value:  10        |
   +---------------------+
          |
          V
   After a goal:
   +---------------------+
   |   name: "score"     |
   +---------------------+
   |   value:  11        |
   +---------------------+
    

Data type flowchart

   Start
     |
     V
   Is it a number? ----> Yes ----> data type: Number
     |
     No
     |
     V
   Is it in quotes? ----> Yes ----> data type: String
     |
     No
     |
     V
   Is it true/false? ----> Yes ----> data type: Boolean
     |
     No
     |
     V
   Is it undefined? ----> Yes ----> data type: Undefined
     |
     No
     |
     V
   It might be null or object.
    

Timeline: The life of a variable

   1. Declare:    let score;
   2. Assign:     score = 0;
   3. Use:        console.log(score);
   4. Change:     score = 10;
   5. Use again:  console.log(score);
    

📋 Comparison Tables

let vs const vs var

KeywordCan change?When to use
letYesFor values that will change.
constNoFor values that stay the same.
varYesOld code; avoid in new code.

Data type summary

TypeExampleUsed for
Number42, 3.14Math, counting, measuring
String"Ada", 'Lagos'Text, names, messages
Booleantrue, falseDecisions, yes/no
Undefinedlet x;No value yet
Nulllet y = null;Empty on purpose

📝 Summary After Every Lesson

Each lesson above ended with a Mini Summary. That’s your quick recap. If you forget something, go back to that lesson and read the mini summary again.

🎓 End-of-Module Summary

In this module, you learned that variables are named containers for data. You discovered how to create them with let, const, and var (but we prefer let and const). You explored the main data types: numbers, strings, booleans, undefined, and null. You learned how to change values, combine strings, use template literals, check types with typeof, and convert between types. You also saw many examples from Nigeria, home, school, and fun games. You are now ready to use variables in your own web projects!

❓ Frequently Asked Questions

  1. What is a variable? A named container that stores a value.
  2. What is a data type? The kind of value, like number or string.
  3. Why use const instead of let? To prevent accidental changes.
  4. Can I change a const variable? No, it will cause an error.
  5. What does undefined mean? A variable has been declared but has no value yet.
  6. What is the difference between null and undefined? null is given on purpose; undefined happens automatically.
  7. How do I combine text and variables? Use + or template literals with ${}.
  8. What is typeof for? It tells you the data type of a value.
  9. How do I convert a string to a number? Use Number("123").
  10. Can variable names have spaces? No, use camelCase or underscores.

🔗 Matching Exercises

Match the item on the left with its correct data type on the right.

ItemData Type
1. "Lagos"A. Number
2. 42B. String
3. trueC. Boolean
4. let x;D. Undefined
5. nullE. Null

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

🎭 Scenario-based Exercises

  1. You are making a game. The player’s score starts at 0. They earn 10 points. What variable would you create and how would you update it?
  2. A user types their age in a form. It arrives as a string "15". How do you calculate their age next year?
  3. You want to display “Welcome, Ada!” on a web page. What data type is “Ada”? How do you combine it with “Welcome, ”?
  4. You are building a weather app. You need to store the temperature (25.5) and whether it is raining (false). What data types are these?
  5. Your friend’s name is not saved in your phone. What value does that contact name have? (Hint: undefined or null?)

👥 Group Activity

“Variable Boxes” Game

Work in groups of 3 or 4. Each group gets three paper boxes (or drawn boxes). Label them “Number”, “String”, “Boolean”. Then one person reads out a value (e.g., “12”, “Ada”, “true”, “false”, “Lagos”, “3.14”). The group must quickly put the value in the correct box. After 10 values, switch roles. The group with the most correct placements wins!

✍️ Individual Activity

Write down 5 variables you would use to describe yourself. For each, write the variable name, the value, and the data type. Example:

  • let myName = "Ada"; — String
  • let myAge = 12; — Number
  • let likesJollof = true; — Boolean
  • let favouriteSubject = "Maths"; — String
  • let shoeSize = 36; — Number

🛠️ Mini Project: “About Me” Card

Create a simple web page (or a plain text file) that uses variables to display information about you. Use at least 4 variables of different data types. Then combine them into a sentence using template literals.

Example:

   let name = "Ada";
   let age = 12;
   let city = "Lagos";
   let likesCoding = true;
   let message = `My name is ${name}. I am ${age} years old. I live in ${city}. It is ${likesCoding} that I like coding.`;
   console.log(message);
    

You can write this in a JavaScript file and run it in your browser’s console, or just write it on paper and show your teacher.

📝 Practical Assignment

  1. Create three variables: yourName (string), yourAge (number), isStudent (boolean).
  2. Print a message using template literals that says: “My name is [name]. I am [age] years old. Am I a student? [true/false].”
  3. Change yourAge to your age next year. Print the new message.
  4. Use typeof on each variable and print the results.

🔑 Key Takeaways

  • Variables are named containers for data.
  • Use let for changing values, const for fixed values.
  • Main data types: number, string, boolean, undefined, null.
  • Strings need quotes; numbers and booleans do not.
  • Combine strings with + or template literals.
  • Check types with typeof; convert with Number() and String().
  • Clear names and consistent style make code readable.

💬 Classroom Discussion Questions

  1. Why do we need variables in a web page?
  2. What happens if you try to change a const variable?
  3. Give an example of a number, a string, and a boolean from your daily life.
  4. What is the difference between undefined and null?
  5. Why is it important to use the correct data type?
  6. How can template literals make coding easier?
  7. What would happen if you added a number and a string together in JavaScript?

🚀 Preparation for the Next Module

In Module Four, we will learn about Operators and Expressions. You will discover how to do math with variables, compare values, and make decisions using if statements. To get ready, make sure you are comfortable creating variables and knowing their data types. Try the practical assignment above. When you are ready, turn the page and let’s continue your coding adventure!

End of Module Three

5

Module Four

Module Four: More About Variables & Data Types for the Web

📘 Module Four: More About Variables & Data Types for the Web

Part of the “Web Basics for Young Coders” course — written for curious 10‑ to 13‑year‑olds.

🌟 Module Introduction

In Module Three, you learned that variables are like labelled boxes. You learned how to create them, name them, and store different kinds of data — numbers, strings, booleans, undefined, and null. You also learned how to change values, combine strings, and check data types with typeof.

Now it is time to go deeper. In Module Four, we will explore special ways to work with data. You will learn how to change data types on purpose, how to work with more complex data like arrays and objects, how to use special values carefully, and how to avoid common traps that confuse beginners.

Think of Module Three as learning to ride a bicycle with training wheels. Module Four is where we take the training wheels off and learn to turn, brake, and go faster — safely. You will still use everything you learned before, but now you will become a stronger, smarter coder.

This module has 13 lessons. Each lesson is short and clear. Take your time. Try the examples. Ask questions. By the end, you will be able to build small web programs that store and change real information — just like real websites do.

Let’s begin!

🎯 Learning Objectives

After finishing this module, you will be able to:

  • Explain why data types matter and how JavaScript treats them.
  • Convert between numbers, strings, and booleans using Number(), String(), and Boolean().
  • Understand the difference between primitive types and objects.
  • Create and use arrays to store lists of data.
  • Create and use objects to store related information.
  • Use template literals confidently with different data types.
  • Recognise and avoid common mistakes with undefined, null, and NaN.
  • Use typeof and simple checks to verify data.
  • Write clean, readable code with good variable names.
  • Build a mini project that uses arrays, objects, and type conversion.

📖 Warm-up Story: Chidi and the Market List

Chidi lives in Enugu, Nigeria. Every Saturday, his mother sends him to the market with a list. One Saturday, the list said: “Buy 3 yams, 2 tomatoes, 1 tin of milk, and check if the price of rice is below ₦1000 per cup.”

Chidi looked at the list and thought, “This is not just one thing. This is a list of things. And each thing has a name and a number.” He decided to organise it in his notebook like this:

   Item        | Quantity
   ------------|---------
   Yam         | 3
   Tomato      | 2
   Milk        | 1
   Rice price  | below 1000? (true/false)
    

When he got to the market, he checked the rice price. It was ₦950 per cup. So he wrote “true” next to “Rice price below ₦1000?”. He bought everything and went home.

In web programming, Chidi’s notebook is like an array (a list of items) and an object (a collection of related information). In this module, you will learn how to build these powerful tools. You will also learn how to convert data when needed — like changing a price written as text into a real number so you can compare it.

Are you ready to become a data master? Let’s go!

📚 Lesson 1: Why Data Types Really Matter

Definition

A data type is the kind of value a variable holds — number, string, boolean, and so on.

Why it is important

JavaScript treats each type differently. If you mix them up, you can get strange results that are hard to find.

Simple explanation

Imagine you have a box of eggs and a box of stones. If you try to bounce them, the eggs break. Different things behave differently. In JavaScript, numbers add, strings join, and booleans help make choices.

Real-life example

If a shop’s price is stored as text ("500") instead of a number (500), adding two prices might give "500300" instead of 800.

School example

If your test scores are strings, averaging them will not work correctly.

Home example

If your shopping list total is a string, you cannot calculate change properly.

Nigerian example

If bus fares are strings, adding them gives "500300" instead of 800 naira.

Illustration

   let a = 5;        // number
   let b = "5";      // string
   console.log(a + a);  // 10
   console.log(b + b);  // "55"
    

Mini summary

Always use the correct data type for the job. Numbers for math, strings for text, booleans for yes/no.

📚 Lesson 2: Primitive Types vs Objects

Definition

Primitive types are simple, single values (number, string, boolean, undefined, null, symbol). Objects are collections that can hold many values.

Why it is important

Primitives are copied by value. Objects are copied by reference. This changes how they behave when you change them.

Simple explanation

A primitive is like a single coin. An object is like a wallet that holds many coins and cards.

Real-life example

Your age is a primitive (one number). Your school bag is an object (holds books, pens, snacks).

School example

A single test score is a primitive. A report card is an object (holds scores for many subjects).

Home example

The number of eggs is a primitive. The fridge is an object (holds eggs, milk, vegetables).

Nigerian example

One naira coin is a primitive. A purse full of naira notes and coins is an object.

Illustration

   Primitive:  let age = 12;
   Object:     let student = { name: "Ada", age: 12, class: "JSS2" };
    

Mini summary

Primitives are single values. Objects hold many values together. We will learn more about objects later in this module.

📚 Lesson 3: Converting Between Numbers and Strings

Definition

Type conversion means changing a value from one type to another.

Why it is important

User input from forms always arrives as strings. To do math, you must convert to numbers.

Simple explanation

Use Number("123") to turn text into a number. Use String(123) to turn a number into text.

Real-life example

When you type your age in a form, it arrives as "12". Convert it to 12 to add 1 for next year.

School example

If your score is given as "85", convert it to 85 to find the class average.

Home example

If your recipe says "3" cups of rice, convert to 3 to double the recipe.

Nigerian example

If a trader says the price is "₦500" (string), convert the numeric part to 500 to calculate change.

Illustration

   let strNum = "10";
   let num = Number(strNum);   // 10
   let backToStr = String(num); // "10"
   console.log(typeof num);     // "number"
   console.log(typeof backToStr); // "string"
    

Mini summary

Use Number() and String() to switch between types when needed.

📚 Lesson 4: Converting to Booleans (Truthy and Falsy)

Definition

Boolean() converts a value to true or false. Some values are “falsy” (become false) and others are “truthy” (become true).

Why it is important

This helps you check if something exists, is empty, or is zero.

Simple explanation

Falsy values include: false, 0, "" (empty string), null, undefined, and NaN. Everything else is truthy.

Real-life example

An empty plate is falsy (no food). A plate with food is truthy.

School example

An empty notebook (0 pages written) is falsy. A notebook with notes is truthy.

Home example

A phone with 0% battery is falsy. A phone with 50% battery is truthy.

Nigerian example

An empty fuel tank (0 litres) is falsy. A tank with fuel is truthy.

Illustration

   Boolean(0);        // false
   Boolean("");       // false
   Boolean("hello");  // true
   Boolean(42);       // true
   Boolean(null);     // false
    

Mini summary

Falsy values: false, 0, "", null, undefined, NaN. Everything else is truthy.

📚 Lesson 5: The Mysterious NaN

Definition

NaN means “Not a Number”. It appears when you try to do math with something that is not a number.

Why it is important

NaN can silently break your calculations. You must check for it.

Simple explanation

If you try to multiply "hello" * 2, you get NaN. It is JavaScript’s way of saying “I cannot do this math.”

Real-life example

If you try to add your name to a number, you get a strange result — that is like NaN.

School example

If a test score is missing and you try to average it, you might get NaN.

Home example

If a recipe says “add some salt” (no number) and you try to double it, you get NaN.

Nigerian example

If a price tag is torn and you try to add it, you get NaN — not a number.

Illustration

   let result = "hello" * 2;
   console.log(result);        // NaN
   console.log(typeof result); // "number" (NaN is a number type!)
    

Mini summary

NaN means “Not a Number”. It appears when math fails. Use isNaN() to check for it.

📚 Lesson 6: Introduction to Arrays

Definition

An array is a list of values stored in one variable. You use square brackets [ ].

Why it is important

Arrays let you store many items — like a shopping list or a list of scores — without making many variables.

Simple explanation

Instead of let item1 = "Yam"; let item2 = "Tomato";, you write let items = ["Yam", "Tomato", "Milk"];.

Real-life example

Your playlist is an array of songs. Your contacts list is an array of names.

School example

Your list of subject scores is an array: [85, 90, 78, 92].

Home example

Your shopping list is an array: ["Rice", "Beans", "Oil"].

Nigerian example

The Super Eagles starting eleven is an array of player names: ["Okoye", "Omeruo", "Ajayi", ...].

Illustration

   let fruits = ["Mango", "Orange", "Banana"];
   console.log(fruits[0]); // "Mango"
   console.log(fruits.length); // 3
    

Mini summary

Arrays store lists of values. Use square brackets. Access items with their index starting at 0.

📚 Lesson 7: Working with Arrays (Push, Pop, and Length)

Definition

Arrays have built-in tools (methods) to add, remove, and count items.

Why it is important

Lists change all the time. You need to add new items and remove old ones.

Simple explanation

  • push() adds an item to the end.
  • pop() removes the last item.
  • length tells you how many items there are.

Real-life example

Adding a new contact to your phone (push). Deleting the last message (pop).

School example

Adding a new score to your list (push). Removing the last score (pop).

Home example

Adding “Eggs” to your shopping list (push). Removing the last item you already bought (pop).

Nigerian example

Adding a new player to the Super Eagles squad (push). Removing a player who is injured (pop).

Illustration

   let items = ["Yam", "Tomato"];
   items.push("Milk");   // ["Yam", "Tomato", "Milk"]
   items.pop();          // ["Yam", "Tomato"]
   console.log(items.length); // 2
    

Mini summary

Use push() to add, pop() to remove, and .length to count items in an array.

📚 Lesson 8: Introduction to Objects

Definition

An object is a collection of related information stored as key–value pairs. You use curly braces { }.

Why it is important

Objects let you group related data together — like a student’s name, age, and class.

Simple explanation

Think of a student ID card. It has a name, an age, a class, and a photo. All those pieces belong together. That is an object.

Real-life example

Your phone contact is an object: { name: "Ada", phone: "08012345678", email: "ada@mail.com" }.

School example

A student record: { name: "Chidi", age: 13, class: "JSS3", scores: [85, 90] }.

Home example

A recipe: { name: "Jollof Rice", servings: 4, time: "45 minutes" }.

Nigerian example

A state record: { name: "Lagos", capital: "Ikeja", population: 15000000 }.

Illustration

   let student = {
       name: "Ada",
       age: 12,
       class: "JSS2",
       likesCoding: true
   };
   console.log(student.name); // "Ada"
    

Mini summary

Objects store related data as key–value pairs. Use dot notation (student.name) to read values.

📚 Lesson 9: Arrays Inside Objects (and Objects Inside Arrays)

Definition

You can put arrays inside objects and objects inside arrays. This creates rich data structures.

Why it is important

Real-world data is often nested. A class has many students. Each student has many scores.

Simple explanation

Think of a school as an object. Inside it, there is an array of students. Each student is an object with their own scores (another array).

Real-life example

A music app: an artist object with an array of albums. Each album has an array of songs.

School example

A class object with an array of student objects. Each student has an array of subject scores.

Home example

A fridge object with an array of shelf arrays, each holding items.

Nigerian example

A football team object with an array of player objects, each with their own stats.

Illustration

   let school = {
       name: "Bright Future Academy",
       students: [
           { name: "Ada", age: 12, scores: [85, 90] },
           { name: "Chidi", age: 13, scores: [78, 88] }
       ]
   };
   console.log(school.students[0].name); // "Ada"
   console.log(school.students[0].scores[1]); // 90
    

Mini summary

You can nest arrays and objects. Use dot and bracket notation to reach inside.

📚 Lesson 10: The Difference Between null, undefined, and NaN

Definition

  • undefined: a variable has no value yet.
  • null: an empty value given on purpose.
  • NaN: “Not a Number” — a failed math result.

Why it is important

They look similar but mean different things. Confusing them causes bugs.

Simple explanation

undefined is like an empty box you forgot to fill. null is like a box you deliberately left empty. NaN is like a broken calculator showing an error.

Real-life example

Your friend’s phone number is undefined if you never saved it. Your lunch box is null if you decided to fast. Your maths answer is NaN if you tried to add “hello” to 5.

School example

A test score is undefined if you were absent. A homework mark is null if the teacher chose not to grade it. A calculated average is NaN if one score was text instead of a number.

Home example

The TV remote battery level is undefined if the remote is broken. Your pocket money is null if you spent it all. The total bill is NaN if you typed “five” instead of 5.

Nigerian example

The price of petrol at a closed station is undefined. The number of passengers in an empty bus is null. The total fare is NaN if you added “₦500” to 300 without converting.

Illustration

   let a;              // undefined
   let b = null;       // null
   let c = "hi" * 2;   // NaN
   console.log(typeof a); // "undefined"
   console.log(typeof b); // "object" (a famous quirk)
   console.log(typeof c); // "number"
    

Mini summary

undefined = no value yet. null = empty on purpose. NaN = failed math. Learn to tell them apart.

📚 Lesson 11: Checking Data Types Safely

Definition

You can check data types using typeof, Array.isArray(), and isNaN().

Why it is important

Before you use a value, you should know what type it is. This prevents errors.

Simple explanation

  • typeof x tells you the primitive type.
  • Array.isArray(x) tells you if x is an array.
  • isNaN(x) tells you if x is “Not a Number”.

Real-life example

Before cooking, you check if the ingredient is salt or sugar. Before using a value, check its type.

School example

Before grading, check if the answer is a number or a word.

Home example

Before using a remote, check if it is for the TV or the fan.

Nigerian example

Before accepting a naira note, check if it is ₦1000 or ₦500.

Illustration

   let age = 12;
   let fruits = ["Mango", "Orange"];
   let broken = "hello" * 2;

   console.log(typeof age);          // "number"
   console.log(Array.isArray(fruits)); // true
   console.log(isNaN(broken));        // true
    

Mini summary

Use typeof for primitives, Array.isArray() for arrays, and isNaN() to check for NaN.

📚 Lesson 12: Good Variable Names (Revisited)

Definition

Good variable names describe what the variable holds. They make code easy to read.

Why it is important

You will read your code many times. Clear names save you from confusion.

Simple explanation

Use camelCase: playerScore, favouriteFood, isLoggedIn.

Real-life example

Label kitchen jars “Rice”, “Beans”, “Sugar” — not “Jar1”, “Jar2”.

School example

Name your notebooks “Maths”, “English”, “Science” — not “Book1”, “Book2”.

Home example

Name phone contacts “Mum”, “Dad”, “Ada” — not “Contact1”, “Contact2”.

Nigerian example

Name your variables jollofRicePortions not jrp. Clear names help everyone.

Illustration

   ✅ let playerScore = 100;
   ✅ let isGameOver = false;
   ✅ let favouriteNigerianFood = "Jollof Rice";
   ❌ let x = 100;
   ❌ let y = false;
    

Mini summary

Use clear, descriptive names. camelCase for multi-word names. Avoid single letters except in loops.

📚 Lesson 13: Putting It All Together – A Student Record

Definition

Now we combine arrays, objects, and type conversion to build a small, useful program.

Why it is important

This is how real web apps store and use data — lists of users, products, scores, and more.

Simple explanation

Let’s create a student object with an array of scores, then calculate the average.

Real-life example

A school app that stores student records and calculates their average score.

School example

A class register that shows “Ada scored 85, 90, 78. Average: 84.33”.

Home example

A shopping list app that stores items and their prices, then calculates the total.

Nigerian example

A football app that stores player stats and calculates goals per match.

Illustration

   let student = {
       name: "Ada",
       scores: [85, 90, 78]
   };

   let total = student.scores[0] + student.scores[1] + student.scores[2];
   let average = total / student.scores.length;

   let message = `${student.name} scored an average of ${average}.`;
   console.log(message);
   // Output: Ada scored an average of 84.33333333333333.
    

Mini summary

Objects + arrays + numbers = powerful data handling. You just built a real data structure!

📖 Key Vocabulary

WordSimple Definition
PrimitiveA simple, single value like a number or string.
ObjectA collection of related values stored as key–value pairs.
ArrayA list of values stored in one variable.
IndexThe position of an item in an array, starting at 0.
ElementAn item inside an array.
PropertyA key–value pair inside an object.
MethodA built-in action for a data type, like push().
Type ConversionChanging a value from one type to another.
TruthyA value that becomes true when converted to boolean.
FalsyA value that becomes false when converted to boolean.
NaN“Not a Number” — a failed math result.
typeofAn operator that tells you the data type.
Array.isArray()A method that checks if a value is an array.
isNaN()A function that checks if a value is NaN.

🔑 Important Concepts

  • Data types behave differently: numbers add, strings join, booleans decide.
  • Primitives are single values; objects and arrays hold many values.
  • Convert types with Number(), String(), and Boolean().
  • Falsy values: false, 0, "", null, undefined, NaN. Everything else is truthy.
  • NaN means “Not a Number” and appears when math fails.
  • Arrays store lists. Use [ ], index starting at 0, and .length.
  • Objects store related data. Use { } and dot notation.
  • You can nest arrays inside objects and objects inside arrays.
  • Use typeof, Array.isArray(), and isNaN() to check types safely.
  • Clear variable names make code easy to read and fix.

🪜 Step-by-Step Explanations

How to create an array and add items

  1. Write let items = [ ]; to create an empty array.
  2. Add items with items.push("Yam");.
  3. Read an item with items[0].
  4. Count items with items.length.
  5. Remove the last item with items.pop();.

How to create an object and read its properties

  1. Write let student = { name: "Ada", age: 12 };.
  2. Read a property with student.name.
  3. Add a new property with student.class = "JSS2";.
  4. Change a property with student.age = 13;.
  5. Check if a property exists with "name" in student.

How to convert a string to a number safely

  1. Get the string: let input = "42";.
  2. Convert: let num = Number(input);.
  3. Check: if (isNaN(num)) { console.log("Not a number!"); }.
  4. Use num in math: num + 8; // 50.

🌍 Real-life Examples

  • Online shop: An array of products, each an object with name, price, and stock.
  • Game: An array of high scores, an object for the current player.
  • Music app: An object for a playlist containing an array of song objects.
  • Weather app: An array of daily temperatures, an object for today’s forecast.
  • Bank app: An array of transactions, each with amount, date, and type.

🇳🇬 Nigerian Examples

  • Market list: let marketList = ["Yam", "Tomato", "Milk"]; (array).
  • Jollof rice recipe: { name: "Jollof Rice", servings: 4, spicy: true } (object).
  • Lagos traffic: let trafficLevels = ["light", "heavy", "go-slow"]; (array).
  • Super Eagles: { team: "Super Eagles", players: ["Okoye", "Omeruo"], goals: 2 }.
  • Nollywood: let movies = [{ title: "The Wedding Party", year: 2016 }, { title: "Living in Bondage", year: 1992 }];.

🎈 Fun Examples Children Can Relate To

  • Video game inventory: let inventory = ["Sword", "Shield", "Potion"];
  • Superhero team: let team = [{ name: "Spider-Boy", power: 8 }, { name: "Fire Girl", power: 9 }];
  • Pizza toppings: let toppings = ["Cheese", "Pepperoni", "Mushroom"];
  • Birthday wishlist: let wishlist = ["Bicycle", "Book", "Game"];
  • Favourite colours: let colours = ["Blue", "Green", "Red"];

🏠 Everyday Examples

  • Phone contacts: An array of contact objects with name, phone, and email.
  • Shopping list: An array of items, each with name and quantity.
  • Alarm settings: An object with time, repeat days, and sound.
  • Weather app: An array of temperatures for the week.
  • Step counter: An array of daily step counts.

👨‍👩‍👧 Parent Tips

  • Encourage your child to explain arrays and objects using everyday lists (shopping, contacts).
  • Ask them to spot data types around the house — prices (numbers), names (strings), on/off (booleans).
  • Let them practise converting types, like changing “50” to 50 to add numbers.
  • Remind them that NaN, undefined, and null are not errors; they are tools.
  • Celebrate small wins — like writing their first array and printing an item.

💡 Interesting Facts

  • The word “array” comes from the Latin “arredare”, meaning to arrange.
  • In JavaScript, arrays are actually special kinds of objects.
  • typeof null returns "object" — a famous bug from 1995 that was never fixed.
  • NaN is the only value in JavaScript that is not equal to itself: NaN === NaN is false.
  • Object keys are always strings (or symbols), even if you write them as numbers.

🤔 Did You Know?

  • You can store a function inside an array or object — that’s how many JavaScript libraries work.
  • Arrays can hold different data types: [42, "hello", true, null].
  • You can have an array of arrays: [[1, 2], [3, 4]] — called a 2D array.
  • Objects can contain other objects: { a: { b: { c: 1 } } } — called nested objects.
  • The length property of an array is always one more than the highest index.

🧠 Remember This

  • Primitives are single values; objects and arrays hold many.
  • Convert types with Number(), String(), and Boolean().
  • Falsy: false, 0, "", null, undefined, NaN.
  • NaN means “Not a Number”.
  • Arrays use [ ], index starts at 0, .length gives count.
  • Objects use { }, access with dot notation.
  • Check types with typeof, Array.isArray(), and isNaN().
  • Clear names make happy coders!

❌ Common Mistakes

MistakeWhy it’s wrongFix
let x = "10"; let y = x + 5;Results in "105" (string) not 15.let y = Number(x) + 5;
let arr = [1, 2, 3]; console.log(arr[3]);Index 3 does not exist — arrays start at 0.Use arr[2] for the third item.
let obj = { name: "Ada" }; console.log(obj[name]);Missing quotes around key.obj["name"] or obj.name
let x = null; console.log(x + 1);null converts to 0, so result is 1 — may surprise you.Check for null before math.
let x = "hello" * 2;Result is NaN, not an error.Use isNaN() to check.

✅ Best Practices

  • Use const by default, and let only when you need to change the value.
  • Give meaningful names: playerScore not x.
  • Use camelCase for multi-word names: myFavouriteFood.
  • Always end statements with a semicolon ;.
  • Use template literals for building messages.
  • Check your data types with typeof, Array.isArray(), and isNaN() when debugging.
  • Keep arrays and objects small and focused.

📊 ASCII Illustrations, Diagrams & Flowcharts

Array as a row of boxes

   Index:   0        1        2
         +--------+--------+--------+
   Array | "Yam"  |"Tomato"| "Milk" |
         +--------+--------+--------+
            |        |        |
            V        V        V
         items[0] items[1] items[2]
    

Object as a labelled filing cabinet

   +---------------------------+
   |        student            |
   +---------------------------+
   | name:   "Ada"             |
   | age:    12                |
   | class:  "JSS2"            |
   | scores: [85, 90, 78]      |
   +---------------------------+
    

Data type decision flowchart

   Start
     |
     V
   Is it a number? ----> Yes ----> Number
     |
     No
     |
     V
   Is it in quotes? ----> Yes ----> String
     |
     No
     |
     V
   Is it true/false? ----> Yes ----> Boolean
     |
     No
     |
     V
   Is it an array? ----> Yes ----> Array
     |
     No
     |
     V
   Is it an object? ----> Yes ----> Object
     |
     No
     |
     V
   It might be undefined, null, or NaN.
    

Timeline: Building a student record

   1. Create object:   let student = {};
   2. Add name:        student.name = "Ada";
   3. Add scores:      student.scores = [85, 90, 78];
   4. Calculate total: let total = 85 + 90 + 78;
   5. Calculate average: let avg = total / 3;
   6. Display message: console.log(`${student.name}: ${avg}`);
    

📋 Comparison Tables

Primitive vs Object

FeaturePrimitiveObject
Example42, "Ada", true[1,2,3], { name: "Ada" }
HoldsOne valueMany values
Copied byValueReference
Mutable?No (value is replaced)Yes (contents can change)

undefined vs null vs NaN

ValueMeaningExample
undefinedNo value yetlet x;
nullEmpty on purposelet y = null;
NaNFailed math"hi" * 2

Array vs Object

FeatureArrayObject
Syntax[ ]{ }
AccessBy index (0, 1, 2…)By key (name, age…)
Best forLists of similar itemsRelated information
Example["Yam", "Tomato"]{ name: "Ada", age: 12 }

📝 Summary After Every Lesson

Each lesson above ended with a Mini Summary. That’s your quick recap. If you forget something, go back to that lesson and read the mini summary again.

🎓 End-of-Module Summary

In this module, you went deeper into variables and data types. You learned why data types matter, how primitives differ from objects, and how to convert between numbers, strings, and booleans. You discovered truthy and falsy values, and you met NaN — “Not a Number”. You learned how to create and use arrays to store lists, and objects to store related information. You even combined arrays and objects to build rich data structures. You learned to check types safely with typeof, Array.isArray(), and isNaN(). Finally, you practised good naming and avoided common mistakes. You are now ready to use these tools in real web projects!

❓ Frequently Asked Questions

  1. What is the difference between a primitive and an object? A primitive is a single value; an object holds many values.
  2. How do I convert a string to a number? Use Number("123").
  3. What does NaN mean? “Not a Number” — a failed math result.
  4. What are falsy values? false, 0, "", null, undefined, NaN.
  5. How do I create an array? Use square brackets: let arr = [1, 2, 3];
  6. How do I access an item in an array? Use its index: arr[0] for the first item.
  7. How do I create an object? Use curly braces: let obj = { name: "Ada" };
  8. How do I read a property from an object? Use dot notation: obj.name.
  9. How do I check if something is an array? Use Array.isArray(value).
  10. How do I check for NaN? Use isNaN(value).

🔗 Matching Exercises

Match the item on the left with its correct description on the right.

ItemDescription
1. [1, 2, 3]A. Object
2. { name: "Ada" }B. Array
3. "hello" * 2C. NaN
4. let x;D. Undefined
5. nullE. Empty on purpose

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

🎭 Scenario-based Exercises

  1. You are making a game. The player has an inventory array: ["Sword", "Shield"]. They pick up a potion. How do you add it?
  2. A user types their age in a form. It arrives as "15". How do you calculate their age next year?
  3. You want to display “Welcome, Ada!” on a web page. What data type is “Ada”? How do you combine it with “Welcome, ”?
  4. You are building a weather app. You need to store the temperature (25.5) and whether it is raining (false). What data types are these?
  5. Your friend’s name is not saved in your phone. What value does that contact name have? (Hint: undefined or null?)
  6. You have an array of scores: [85, 90, 78]. How do you find the average?
  7. You have an object: { name: "Ada", age: 12 }. How do you add a new property class: "JSS2"?

👥 Group Activity

“Data Type Sorting” Game

Work in groups of 3 or 4. Each group gets a set of cards with values on them (e.g., 42, "Lagos", true, [1,2,3], { name: "Ada" }, null, undefined, NaN). On the board, write five categories: Number, String, Boolean, Array, Object. One person reads a value. The group must place it in the correct category. After 10 values, switch roles. The group with the most correct placements wins!

✍️ Individual Activity

Write down 5 variables you would use to describe your school bag. For each, write the variable name, the value, and the data type. Example:

  • let bagColour = "Blue"; — String
  • let numberOfBooks = 5; — Number
  • let hasLunch = true; — Boolean
  • let books = ["Maths", "English", "Science"]; — Array
  • let owner = { name: "Ada", age: 12 }; — Object

🛠️ Mini Project: “My Class List”

Create a simple web page (or a plain text file) that uses an array of student objects to display information about your class. Each student object should have a name, age, and an array of scores. Then calculate the average score for each student and display a message.

Example:

   let myClass = [
       { name: "Ada", age: 12, scores: [85, 90, 78] },
       { name: "Chidi", age: 13, scores: [78, 88, 92] },
       { name: "Ngozi", age: 12, scores: [95, 89, 94] }
   ];

   for (let i = 0; i < myClass.length; i++) {
       let student = myClass[i];
       let total = student.scores[0] + student.scores[1] + student.scores[2];
       let average = total / student.scores.length;
       console.log(`${student.name} (age ${student.age}) scored an average of ${average}.`);
   }
    

You can write this in a JavaScript file and run it in your browser’s console, or just write it on paper and show your teacher.

📝 Practical Assignment

  1. Create an array called fruits with 4 fruit names.
  2. Add a fifth fruit using push().
  3. Remove the last fruit using pop().
  4. Print the length of the array.
  5. Create an object called myPet with properties: name, type, age, and isFriendly.
  6. Print a message using template literals that describes your pet.
  7. Use typeof on each property and print the results.

🔑 Key Takeaways

  • Primitives are single values; objects and arrays hold many.
  • Convert types with Number(), String(), and Boolean().
  • Falsy values: false, 0, "", null, undefined, NaN.
  • NaN means “Not a Number”.
  • Arrays use [ ], index starts at 0, .length gives count.
  • Objects use { }, access with dot notation.
  • Check types with typeof, Array.isArray(), and isNaN().
  • Clear names and consistent style make code readable.

💬 Classroom Discussion Questions

  1. Why do we need arrays and objects in a web page?
  2. What is the difference between a primitive and an object?
  3. Give an example of a number, a string, a boolean, an array, and an object from your daily life.
  4. What is the difference between undefined, null, and NaN?
  5. Why is it important to convert types correctly?
  6. How can template literals make coding easier?
  7. What would happen if you added a number and a string together in JavaScript?

🚀 Preparation for the Next Module

In Module Five, we will learn about Operators and Expressions. You will discover how to do math with variables, compare values, and make decisions using if statements. You will also learn about logical operators (&&, ||, !) and how to combine conditions. To get ready, make sure you are comfortable creating variables, using arrays and objects, and checking data types. Try the practical assignment above. When you are ready, turn the page and let’s continue your coding adventure!

End of Module Four

🏆 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.
→