"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
“Variables & Data Types for Web” – Learn how JavaScript remembers information
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!
After finishing this module, you will be able to:
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.
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.
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.
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:
let or const.=.;.Mini summary: Creating a variable means giving it a name and a value.
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.
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:
totalSales).let.Mini summary: Use clear, descriptive names in camelCase.
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.
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.
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.
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.
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.
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.
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:
let name = "Ada"; and press Enter.name and press Enter to see the value.Mini summary: The browser console is your safe playground for testing variables.
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.
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:
| Mistake | What Happens | How to Fix |
|---|---|---|
| Starting name with a number | Syntax error | Start with a letter |
| Using reserved words | Syntax error | Pick another name |
| Reassigning const | Error | Use let if value changes |
| Mixing types | Wrong result | Use correct type |
| Forgetting semicolon | Error | Add ; at the end |
| Using undefined value | undefined result | Check before use |
Mini summary: Common mistakes: bad names, mixing types, missing semicolons.
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:
const by default.let only when the value changes.typeof.Mini summary: Best practices: const by default, clear names, correct types.
You now have a strong foundation in variables and data types.
What you learned:
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!
| Word | Simple Definition |
|---|---|
| Variable | A named container for a value. |
| Value | Any piece of data (number, text, etc.). |
| Data Type | The kind of value (number, string, etc.). |
| let | Creates a variable that can change. |
| const | Creates a variable that cannot change. |
| Number | A numeric value like 5 or 3.14. |
| String | A text value like "Hello". |
| Boolean | A true or false value. |
| Null | A special value meaning "nothing". |
| Undefined | A value that has not been set. |
| Object | A collection of key-value pairs. |
| Array | A list of values. |
| typeof | An operator that tells the type of a value. |
| Console | A tool for testing JavaScript. |
| camelCase | A naming style like totalSales. |
let or const.=.;.let name = "Ada";.name and press Enter."Ada".typeof "Hello"."string".let.const.petName = "Buddy".playerScore = 500.favouriteSnack = "Chin Chin".toyCount = 12.booksRead = 5.shoppingTotal = 5000.monthlyBudget = 50000.currentHour = 14.numberOfCups = 2.distanceKm = 120.let without a value?a = b = 5?+-----------+ | name: Ada | +-----------+ +-----------+ | age: 13 | +-----------+
let → whiteboard (can change) const → stone tablet (cannot change)
Number: 42, 3.14
String: "Hello", "Ada"
Boolean: true, false
Null: null
Undefined: undefined
Object: { name: "Ada" }
Array: [1, 2, 3]
typeof "Hello" → "string" typeof 42 → "number" typeof true → "boolean"
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 🎉
| Feature | let | const |
|---|---|---|
| Can change? | Yes | No |
| Best for | Changing values | Fixed values |
| Example | let score = 90 | const pi = 3.14 |
| Type | Example |
|---|---|
| Number | 42, 3.14 |
| String | "Ada", "Hello" |
| Boolean | true, false |
| Null | null |
| Undefined | undefined |
| Object | { name: "Ada" } |
| Array | [1, 2, 3] |
| Good | Bad |
|---|---|
| customerName | cn |
| totalSales | ts |
| priceOfRice | p |
| monthlyBudget | mb |
| Value | typeof |
|---|---|
| "hi" | string |
| 5 | number |
| true | boolean |
| undefined | undefined |
| null | object |
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.
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.
Match the term to its meaning.
| Term | Meaning |
|---|---|
| 1. Variable | A. The kind of value |
| 2. Data type | B. A named container for a value |
| 3. let | C. Tells the type of a value |
| 4. const | D. A variable that can change |
| 5. typeof | E. A variable that cannot change |
Answers: 1-B, 2-A, 3-D, 4-E, 5-C
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.
Task: In the browser console, create:
Write down each and its result.
Project: “My First JavaScript Profile”
Create a small script with variables that describe you:
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}.`);
Assignment: Ask a family member about a small business. Then write JavaScript that:
Submit: Your code and a short explanation.
In Module Two, we will learn about strings, numbers, and booleans in depth. We will cover:
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
“Variables & Data Types for Web” – Learn how JavaScript remembers information
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!
After finishing this module, you will be able to:
length, toUpperCase, and slice.+ operator and template literals.toFixed and parseInt.Math object for rounding and randomness.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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
| Mistake | What Happens | How to Fix |
|---|---|---|
| Mixing strings and numbers | Wrong result | Convert with Number() |
| Using quotes on numbers | Text instead of number | Remove quotes |
| Forgetting to convert input | Wrong math | Use parseInt/parseFloat |
| Comparing string "5" to number 5 | Wrong equality | Use === or convert |
| Using booleans in math | Unexpected numbers | Keep booleans for logic |
| Assuming text is a number | NaN errors | Check with typeof |
Mini summary: Common mistakes: mixing types, forgetting to convert, and using quotes on numbers.
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:
toFixed when showing money.Math.round when displaying whole numbers.Mini summary: Best practices: template literals, type conversion, and clean code.
You now know how to work with strings, numbers, and booleans.
What you learned:
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.
| Word | Simple Definition |
|---|---|
| String | Text inside quotes. |
| Number | A numeric value like 5 or 3.14. |
| Boolean | A true or false value. |
| Template literal | A string using backticks and ${ }. |
| Method | A built-in tool that works on a value. |
| Concatenation | Joining strings with +. |
| parseInt | Converts a string to a whole number. |
| parseFloat | Converts a string to a decimal number. |
| toFixed | Rounds a number to a set number of decimals. |
| Math | A built-in object of math helpers. |
| typeof | An operator that tells the type of a value. |
| NaN | "Not a Number" — an invalid number value. |
| Type conversion | Changing a value from one type to another. |
| camelCase | A naming style like totalSales. |
| Console | A tool for testing JavaScript. |
let name = "Ada";.console.log(name).name.toUpperCase().name.length.`.${value} inside.let a = 10; and let b = 5;.a + b, a * b, etc.let price = 3000.5678;.price.toFixed(2)."3000.57".let isOpen = true;.isOpen.false to see the other result.toFixed(2).petName.toUpperCase().Math.random() for random dice.toFixed(2).toFixed(2).String: "Ada" → text Number: 42, 3.14 → math Boolean: true, false → decisions
"Hello, " + "Ada" → "Hello, Ada"
`Hello, ${name}!`
Math.round(4.6) → 5 Math.floor(4.9) → 4 Math.ceil(4.1) → 5
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 🎉
| Feature | String | Number |
|---|---|---|
| Example | "Ada" | 42 |
| Quotes | Yes | No |
| Math | No | Yes |
| Length | Yes | No |
| Feature | Number | Boolean |
|---|---|---|
| Values | Any number | true or false |
| Use | Math | Decisions |
| Example | 42 | true |
| Method | What it does |
|---|---|
| length | Counts characters |
| toUpperCase() | Makes all caps |
| toLowerCase() | Makes all small |
| slice() | Cut a piece |
| includes() | Check for text |
| trim() | Remove extra spaces |
| Conversion | Example | Result |
|---|---|---|
| String → Number | Number("500") | 500 |
| Number → String | String(500) | "500" |
| Any → Boolean | Boolean(1) | true |
| Text → Integer | parseInt("500") | 500 |
| Text → Decimal | parseFloat("50.5") | 50.5 |
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.
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.
toFixed(2).Match the term to its meaning.
| Term | Meaning |
|---|---|
| 1. String | A. A true or false value |
| 2. Number | B. Text inside quotes |
| 3. Boolean | C. A built-in math tool |
| 4. Math | D. A numeric value |
| 5. typeof | E. Tells the type of a value |
Answers: 1-B, 2-D, 3-A, 4-C, 5-E
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.
Task: In the browser console, create:
Write down each and its result.
Project: “My First Shop Receipt”
Create a JavaScript receipt with:
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)}`);
Assignment: Ask a family member about a small business. Then write JavaScript that:
toFixed(2).Submit: Your code and a short explanation.
toFixed(2) do?In Module Three, we will learn about objects, arrays, and special types. We will cover:
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
Part of the “Web Basics for Young Coders” course — written for curious 10‑ to 13‑year‑olds.
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!
After finishing this module, you will be able to:
let, const, and var.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!
A variable is a named container that stores a value. You can think of it as a labelled box where you keep information.
Without variables, your web page would forget everything. Variables let you save data, change it, and use it again.
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).
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.
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.
Your phone’s battery percentage is a variable called batteryLevel. It changes from 100 to 99 to 98…
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.
+-------------------+
| variable name |
| "score" |
+-------------------+
| value: 10 |
+-------------------+
|
V
Later, value becomes 15
A variable is a labelled container that holds a value. You can change the value whenever you want.
Creating a variable means declaring it and giving it a name. In JavaScript we use keywords like let, const, or var.
You must tell the computer that you want a new container. The keyword is like saying “Hey computer, I’m making a new box!”
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).
let is like a whiteboard — you can erase and write again. const is like a carved stone — once written, it stays.
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).
The TV volume (let volume = 10) can change. Your date of birth (const birthday = "12 May 2012") never changes.
let fuelPrice = 600 (price changes often). const country = "Nigeria" (never changes).
let score = 0; // can change
const PI = 3.14; // cannot change
var oldStyle = "ok"; // older way
Use let for values that change, const for values that stay the same, and avoid var unless you see it in old code.
Variable names are the labels you give to your boxes. They must follow certain rules.
Good names make your code easy to read. Bad names confuse you and others.
$, and _.let, const, if (reserved words).score and Score are different.Naming a dog “Dog” is confusing. Naming it “Bingo” is better. So name your variable playerScore not s.
Instead of calling your notebook “book1”, call it “MathsNotes”.
Label your kitchen jars “Rice”, “Beans”, “Sugar” — not “Jar1”, “Jar2”.
Call your variable jollofRicePortions not jrp. Clear names help everyone.
✅ let playerScore = 100;
❌ let 2players = 5; // cannot start with number
❌ let my-name = "Ada"; // hyphen not allowed
✅ let my_name = "Ada"; // underscore is fine
Use clear, descriptive names. Start with a letter, $, or _. No spaces or hyphens.
A number data type stores numeric values, like 7, 3.14, or -5.
Numbers are used for scores, prices, ages, calculations, and much more.
You can do math with numbers: add (+), subtract (-), multiply (*), divide (/).
The price of a loaf of bread is a number. Your age is a number.
Your test score is a number. The number of pencils in your bag is a number.
The temperature in the fridge is a number. The number of eggs left is a number.
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.
let age = 12;
let price = 350.50;
let temperature = -3;
Numbers are for counting, measuring, and calculating. No quotes around them.
A string is a sequence of characters (letters, numbers, symbols) wrapped in quotes. It represents text.
Strings hold names, sentences, addresses, and any written information.
Use single quotes ' ', double quotes " ", or backticks ` ` to make a string.
Your name is a string. Your school’s name is a string.
The title of a book is a string. The answer to “What is your favourite subject?” is a string.
A text message you send is a string. Your address is a string.
"Lagos", "Jollof rice", "Nollywood" are all strings.
let name = "Ada";
let city = 'Abuja';
let greeting = `Hello, welcome!`;
Strings are text inside quotes. They can be empty ("") or long.
A boolean has only two possible values: true or false.
Booleans help your program make decisions. For example, “Is the user logged in?” true or false.
Think of a light switch: it is either ON (true) or OFF (false).
“Is it raining?” — true or false. “Do I have money?” — true or false.
“Did I finish my homework?” — true or false.
“Is the door locked?” — true or false.
“Is there fuel in the generator?” — true or false. “Did Nigeria win the match?” — true or false.
let isRaining = true;
let hasMoney = false;
Booleans are yes/no answers written as true or false (no quotes).
undefined means a variable has been declared but has no value yet. null means “no value” on purpose.
They help you know when something is missing or empty.
Imagine a box with no label (undefined) versus a box with a label but deliberately empty (null).
Your friend’s phone number is undefined if you never saved it. Your lunch box is null if you decided to fast today.
A test score is undefined if you were absent. A homework mark is null if the teacher chose not to grade it.
The TV remote battery level is undefined if the remote is broken. Your pocket money is null if you spent it all.
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”).
let score; // undefined
let favouriteFood = null; // intentionally empty
undefined happens automatically when you forget to give a value. null is given on purpose to mean “nothing”.
If you used let, you can give the variable a new value later.
Web pages are dynamic — things change. Scores go up, names change, counters increase.
Just write the variable name again and assign a new value with =.
Your age changes every year. So age = age + 1.
Your class attendance count changes. presentCount = presentCount + 1.
The number of slices of bread decreases. breadSlices = breadSlices - 1.
The Super Eagles score increases: eaglesScore = eaglesScore + 1.
let score = 0;
score = 10; // now score is 10
score = score + 5; // now score is 15
Variables declared with let can be updated. const cannot be updated.
Concatenation means joining strings together using the + operator.
You often need to build messages using variables, like “Hello, Ada!”
Just use + between strings and variables that hold strings.
Writing a greeting card: “Dear” + “ “ + name + “,”
Making a name tag: “Student: ” + studentName
Sending a text: “Good morning, ” + mum
“Welcome to ” + city + “, the centre of excellence!”
let firstName = "Ada";
let greeting = "Hello, " + firstName + "!";
// greeting becomes "Hello, Ada!"
Use + to join strings. Make sure to include spaces where needed.
Template literals let you insert variables inside a string using ${ } and backticks.
They make combining strings easier and cleaner, especially with many variables.
Instead of lots of +, you write one string with placeholders.
Filling a form: “My name is ${name} and I am ${age} years old.”
“Student ${name} scored ${score} marks.”
“Dinner is ${food} and it costs ₦${price}.”
“${player} scored a goal for Nigeria!”
let name = "Ada";
let age = 12;
let message = `My name is ${name} and I am ${age} years old.`;
Use backticks and ${ } to drop variables right into strings.
Data types tell the computer how to treat a value — as a number, text, true/false, etc.
If you mix types, you can get strange results. For example, "5" + 5 gives "55" (string), not 10.
Numbers add. Strings join. Booleans help make decisions. Using the wrong type is like putting water in a petrol tank.
If a shop’s price is stored as a string, adding two prices might join them instead of adding them.
If your test scores are strings, averaging them will give a weird result.
If your shopping list total is a string, you cannot calculate change.
If bus fares are strings, adding them gives “500300” instead of 800.
let a = 5; // number
let b = "5"; // string
console.log(a + a); // 10
console.log(b + b); // "55"
Always use the correct data type for the job. Numbers for math, strings for text.
typeoftypeof is an operator that tells you the data type of a value.
It helps you find mistakes when your code behaves strangely.
Just write typeof variableName and it returns a string like "number" or "string".
Like checking the label on a food packet to see if it’s sugar or salt.
Like checking if an answer is a number or a word before marking it.
Like checking if the remote control is for the TV or the fan.
Like checking if a naira note is ₦1000 or ₦500 before using it.
let age = 12;
console.log(typeof age); // "number"
let name = "Ada";
console.log(typeof name); // "string"
typeof is your friend. Use it to check what type a variable holds.
Sometimes you need to change a string to a number, or a number to a string. This is called type conversion.
User input from a web page often comes as strings. You must convert them to numbers for math.
Use Number() to turn a string into a number. Use String() to turn a number into a string.
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.
If your test score is given as “85” (string), you convert it to 85 to find the average.
If your shopping list says “3” apples, you convert it to 3 to count them.
If a bus conductor says “₦500” (string), you convert to 500 to give correct change.
let strNum = "10";
let num = Number(strNum); // 10
let backToStr = String(num); // "10"
Use Number() and String() to switch between types when needed.
A constant is a variable whose value cannot be changed after it is set. In JavaScript we use const.
Some values should never change: your birth date, the value of PI, the name of your country.
Think of a carved stone tablet. Once written, it stays forever. That’s const.
Your national identity number is a constant. Your school’s name is a constant.
The school’s motto is a constant. The number of days in a week (7) is a constant.
Your house address is a constant. The number of months in a year (12) is a constant.
“Nigeria” is a constant. The number of states (36) is a constant.
const BIRTH_YEAR = 2012;
// BIRTH_YEAR = 2013; ❌ Error: cannot change
Use const for values that must stay the same. It prevents accidental changes.
Now we combine variables and data types to make a small, useful program.
This is how real web pages work — they store data in variables and use it to display messages.
Let’s write a program that greets a user and calculates their age next year.
A website that says “Welcome, Ada! You will be 13 next year.”
A class register that shows “Student: Ada, Age: 12, Next year: 13”.
A shopping list that says “3 apples, 2 bread, total 5 items”.
A football app that shows “Super Eagles scored 2 goals. Next match: Nigeria vs Ghana.”
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.
Variables + data types + string concatenation = useful web messages. You just wrote a tiny program!
| Word | Simple Definition |
|---|---|
| Variable | A named box that holds a value. |
| Data Type | The kind of value, like number or text. |
| Number | A numeric value, like 7 or 3.14. |
| String | Text inside quotes, like "hello". |
| Boolean | True or false. |
| Undefined | A variable with no value yet. |
| Null | An empty value given on purpose. |
| Declaration | Creating a variable with let, const, or var. |
| Assignment | Giving a value to a variable using =. |
| Concatenation | Joining strings with +. |
| Template Literal | A string with backticks that can include ${}. |
| Type Conversion | Changing a value from one type to another. |
typeof | An operator that tells you the data type. |
let for changeable values, const for fixed values.let variable but not a const.+ to join strings, but be careful with numbers and strings.` `) make combining strings easier.typeof helps you check data types.Number() and String().let or const.playerScore).= to assign a value (e.g., let playerScore = 0;).let, you can change the value: playerScore = 10;.+ to join: "Score: " + 10 gives "Score: 10".`Score: ${10}`.let price = 1500; (number). let currency = "₦"; (string).let jollofPortions = 3; (number). let isSpicy = true; (boolean).let trafficLevel = "heavy"; (string).let eaglesScore = 2; let opponentScore = 1; let isWinning = true;.let movieTitle = "The Wedding Party"; let releaseYear = 2016;.let lives = 3; After losing a life: lives = lives - 1;let slices = 8; You eat 2: slices = slices - 2;let age = 10; Next year: age = age + 1;let heroName = "Spider-Boy";let likesChocolate = true;let alarmTime = "7:00 AM"; (string).let batteryPercentage = 85; (number).let isLightOn = false; (boolean).let item1 = "Milk"; let item2 = "Bread"; (strings).let steps = 3000; (number).undefined and null are not errors; they are tools.int score = 0;). JavaScript is more relaxed.typeof operator is so useful that it exists in almost every programming language.typeof null returns "object" — a famous bug in JavaScript that was never fixed to avoid breaking old websites.$, or _."123", but they are still text.let for change, const for no change.+ or template literals.typeof.Number() and String().| Mistake | Why it’s wrong | Fix |
|---|---|---|
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"; |
const by default, and let only when you need to change the value.playerScore not x.myFavoriteFood.;.typeof when debugging.
+---------------------+
| name: "score" |
+---------------------+
| value: 10 |
+---------------------+
|
V
After a goal:
+---------------------+
| name: "score" |
+---------------------+
| value: 11 |
+---------------------+
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.
1. Declare: let score;
2. Assign: score = 0;
3. Use: console.log(score);
4. Change: score = 10;
5. Use again: console.log(score);
let vs const vs var| Keyword | Can change? | When to use |
|---|---|---|
let | Yes | For values that will change. |
const | No | For values that stay the same. |
var | Yes | Old code; avoid in new code. |
| Type | Example | Used for |
|---|---|---|
| Number | 42, 3.14 | Math, counting, measuring |
| String | "Ada", 'Lagos' | Text, names, messages |
| Boolean | true, false | Decisions, yes/no |
| Undefined | let x; | No value yet |
| Null | let y = null; | Empty on purpose |
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.
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!
const instead of let? To prevent accidental changes.const variable? No, it will cause an error.undefined mean? A variable has been declared but has no value yet.null and undefined? null is given on purpose; undefined happens automatically.+ or template literals with ${}.typeof for? It tells you the data type of a value.Number("123").Match the item on the left with its correct data type on the right.
| Item | Data Type |
|---|---|
1. "Lagos" | A. Number |
2. 42 | B. String |
3. true | C. Boolean |
4. let x; | D. Undefined |
5. null | E. Null |
Answers: 1-B, 2-A, 3-C, 4-D, 5-E
“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!
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"; — Stringlet myAge = 12; — Numberlet likesJollof = true; — Booleanlet favouriteSubject = "Maths"; — Stringlet shoeSize = 36; — NumberCreate 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.
yourName (string), yourAge (number), isStudent (boolean).yourAge to your age next year. Print the new message.typeof on each variable and print the results.let for changing values, const for fixed values.+ or template literals.typeof; convert with Number() and String().const variable?undefined and null?
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
Part of the “Web Basics for Young Coders” course — written for curious 10‑ to 13‑year‑olds.
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!
After finishing this module, you will be able to:
Number(), String(), and Boolean().undefined, null, and NaN.typeof and simple checks to verify data.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!
A data type is the kind of value a variable holds — number, string, boolean, and so on.
JavaScript treats each type differently. If you mix them up, you can get strange results that are hard to find.
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.
If a shop’s price is stored as text ("500") instead of a number (500),
adding two prices might give "500300" instead of 800.
If your test scores are strings, averaging them will not work correctly.
If your shopping list total is a string, you cannot calculate change properly.
If bus fares are strings, adding them gives "500300" instead of 800 naira.
let a = 5; // number
let b = "5"; // string
console.log(a + a); // 10
console.log(b + b); // "55"
Always use the correct data type for the job. Numbers for math, strings for text, booleans for yes/no.
Primitive types are simple, single values (number, string, boolean, undefined, null, symbol). Objects are collections that can hold many values.
Primitives are copied by value. Objects are copied by reference. This changes how they behave when you change them.
A primitive is like a single coin. An object is like a wallet that holds many coins and cards.
Your age is a primitive (one number). Your school bag is an object (holds books, pens, snacks).
A single test score is a primitive. A report card is an object (holds scores for many subjects).
The number of eggs is a primitive. The fridge is an object (holds eggs, milk, vegetables).
One naira coin is a primitive. A purse full of naira notes and coins is an object.
Primitive: let age = 12;
Object: let student = { name: "Ada", age: 12, class: "JSS2" };
Primitives are single values. Objects hold many values together. We will learn more about objects later in this module.
Type conversion means changing a value from one type to another.
User input from forms always arrives as strings. To do math, you must convert to numbers.
Use Number("123") to turn text into a number. Use String(123) to turn a number into text.
When you type your age in a form, it arrives as "12". Convert it to 12 to add 1 for next year.
If your score is given as "85", convert it to 85 to find the class average.
If your recipe says "3" cups of rice, convert to 3 to double the recipe.
If a trader says the price is "₦500" (string), convert the numeric part to 500 to calculate change.
let strNum = "10";
let num = Number(strNum); // 10
let backToStr = String(num); // "10"
console.log(typeof num); // "number"
console.log(typeof backToStr); // "string"
Use Number() and String() to switch between types when needed.
Boolean() converts a value to true or false. Some values are
“falsy” (become false) and others are “truthy” (become true).
This helps you check if something exists, is empty, or is zero.
Falsy values include: false, 0, "" (empty string),
null, undefined, and NaN. Everything else is truthy.
An empty plate is falsy (no food). A plate with food is truthy.
An empty notebook (0 pages written) is falsy. A notebook with notes is truthy.
A phone with 0% battery is falsy. A phone with 50% battery is truthy.
An empty fuel tank (0 litres) is falsy. A tank with fuel is truthy.
Boolean(0); // false
Boolean(""); // false
Boolean("hello"); // true
Boolean(42); // true
Boolean(null); // false
Falsy values: false, 0, "", null, undefined, NaN. Everything else is truthy.
NaN means “Not a Number”. It appears when you try to do math with something that is not a number.
NaN can silently break your calculations. You must check for it.
If you try to multiply "hello" * 2, you get NaN. It is JavaScript’s way of saying
“I cannot do this math.”
If you try to add your name to a number, you get a strange result — that is like NaN.
If a test score is missing and you try to average it, you might get NaN.
If a recipe says “add some salt” (no number) and you try to double it, you get NaN.
If a price tag is torn and you try to add it, you get NaN — not a number.
let result = "hello" * 2;
console.log(result); // NaN
console.log(typeof result); // "number" (NaN is a number type!)
NaN means “Not a Number”. It appears when math fails. Use isNaN() to check for it.
An array is a list of values stored in one variable. You use square brackets [ ].
Arrays let you store many items — like a shopping list or a list of scores — without making many variables.
Instead of let item1 = "Yam"; let item2 = "Tomato";, you write
let items = ["Yam", "Tomato", "Milk"];.
Your playlist is an array of songs. Your contacts list is an array of names.
Your list of subject scores is an array: [85, 90, 78, 92].
Your shopping list is an array: ["Rice", "Beans", "Oil"].
The Super Eagles starting eleven is an array of player names:
["Okoye", "Omeruo", "Ajayi", ...].
let fruits = ["Mango", "Orange", "Banana"];
console.log(fruits[0]); // "Mango"
console.log(fruits.length); // 3
Arrays store lists of values. Use square brackets. Access items with their index starting at 0.
Arrays have built-in tools (methods) to add, remove, and count items.
Lists change all the time. You need to add new items and remove old ones.
push() adds an item to the end.pop() removes the last item.length tells you how many items there are.Adding a new contact to your phone (push). Deleting the last message (pop).
Adding a new score to your list (push). Removing the last score (pop).
Adding “Eggs” to your shopping list (push). Removing the last item you already bought (pop).
Adding a new player to the Super Eagles squad (push). Removing a player who is injured (pop).
let items = ["Yam", "Tomato"];
items.push("Milk"); // ["Yam", "Tomato", "Milk"]
items.pop(); // ["Yam", "Tomato"]
console.log(items.length); // 2
Use push() to add, pop() to remove, and .length to count items in an array.
An object is a collection of related information stored as key–value pairs. You use curly braces { }.
Objects let you group related data together — like a student’s name, age, and class.
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.
Your phone contact is an object: { name: "Ada", phone: "08012345678", email: "ada@mail.com" }.
A student record: { name: "Chidi", age: 13, class: "JSS3", scores: [85, 90] }.
A recipe: { name: "Jollof Rice", servings: 4, time: "45 minutes" }.
A state record: { name: "Lagos", capital: "Ikeja", population: 15000000 }.
let student = {
name: "Ada",
age: 12,
class: "JSS2",
likesCoding: true
};
console.log(student.name); // "Ada"
Objects store related data as key–value pairs. Use dot notation (student.name) to read values.
You can put arrays inside objects and objects inside arrays. This creates rich data structures.
Real-world data is often nested. A class has many students. Each student has many scores.
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).
A music app: an artist object with an array of albums. Each album has an array of songs.
A class object with an array of student objects. Each student has an array of subject scores.
A fridge object with an array of shelf arrays, each holding items.
A football team object with an array of player objects, each with their own stats.
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
You can nest arrays and objects. Use dot and bracket notation to reach inside.
undefined: a variable has no value yet.null: an empty value given on purpose.NaN: “Not a Number” — a failed math result.They look similar but mean different things. Confusing them causes bugs.
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.
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.
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.
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.
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.
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"
undefined = no value yet. null = empty on purpose. NaN = failed math. Learn to tell them apart.
You can check data types using typeof, Array.isArray(), and
isNaN().
Before you use a value, you should know what type it is. This prevents errors.
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”.Before cooking, you check if the ingredient is salt or sugar. Before using a value, check its type.
Before grading, check if the answer is a number or a word.
Before using a remote, check if it is for the TV or the fan.
Before accepting a naira note, check if it is ₦1000 or ₦500.
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
Use typeof for primitives, Array.isArray() for arrays, and
isNaN() to check for NaN.
Good variable names describe what the variable holds. They make code easy to read.
You will read your code many times. Clear names save you from confusion.
Use camelCase: playerScore, favouriteFood, isLoggedIn.
Label kitchen jars “Rice”, “Beans”, “Sugar” — not “Jar1”, “Jar2”.
Name your notebooks “Maths”, “English”, “Science” — not “Book1”, “Book2”.
Name phone contacts “Mum”, “Dad”, “Ada” — not “Contact1”, “Contact2”.
Name your variables jollofRicePortions not jrp. Clear names help everyone.
✅ let playerScore = 100;
✅ let isGameOver = false;
✅ let favouriteNigerianFood = "Jollof Rice";
❌ let x = 100;
❌ let y = false;
Use clear, descriptive names. camelCase for multi-word names. Avoid single letters except in loops.
Now we combine arrays, objects, and type conversion to build a small, useful program.
This is how real web apps store and use data — lists of users, products, scores, and more.
Let’s create a student object with an array of scores, then calculate the average.
A school app that stores student records and calculates their average score.
A class register that shows “Ada scored 85, 90, 78. Average: 84.33”.
A shopping list app that stores items and their prices, then calculates the total.
A football app that stores player stats and calculates goals per match.
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.
Objects + arrays + numbers = powerful data handling. You just built a real data structure!
| Word | Simple Definition |
|---|---|
| Primitive | A simple, single value like a number or string. |
| Object | A collection of related values stored as key–value pairs. |
| Array | A list of values stored in one variable. |
| Index | The position of an item in an array, starting at 0. |
| Element | An item inside an array. |
| Property | A key–value pair inside an object. |
| Method | A built-in action for a data type, like push(). |
| Type Conversion | Changing a value from one type to another. |
| Truthy | A value that becomes true when converted to boolean. |
| Falsy | A value that becomes false when converted to boolean. |
| NaN | “Not a Number” — a failed math result. |
typeof | An 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. |
Number(), String(), and Boolean().[ ], index starting at 0, and .length.{ } and dot notation.typeof, Array.isArray(), and isNaN() to check types safely.let items = [ ]; to create an empty array.items.push("Yam");.items[0].items.length.items.pop();.let student = { name: "Ada", age: 12 };.student.name.student.class = "JSS2";.student.age = 13;."name" in student.let input = "42";.let num = Number(input);.if (isNaN(num)) { console.log("Not a number!"); }.num in math: num + 8; // 50.let marketList = ["Yam", "Tomato", "Milk"]; (array).{ name: "Jollof Rice", servings: 4, spicy: true } (object).let trafficLevels = ["light", "heavy", "go-slow"]; (array).{ team: "Super Eagles", players: ["Okoye", "Omeruo"], goals: 2 }.let movies = [{ title: "The Wedding Party", year: 2016 }, { title: "Living in Bondage", year: 1992 }];.let inventory = ["Sword", "Shield", "Potion"];let team = [{ name: "Spider-Boy", power: 8 }, { name: "Fire Girl", power: 9 }];let toppings = ["Cheese", "Pepperoni", "Mushroom"];let wishlist = ["Bicycle", "Book", "Game"];let colours = ["Blue", "Green", "Red"];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.[42, "hello", true, null].[[1, 2], [3, 4]] — called a 2D array.{ a: { b: { c: 1 } } } — called nested objects.length property of an array is always one more than the highest index.Number(), String(), and Boolean().[ ], index starts at 0, .length gives count.{ }, access with dot notation.typeof, Array.isArray(), and isNaN().| Mistake | Why it’s wrong | Fix |
|---|---|---|
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. |
const by default, and let only when you need to change the value.playerScore not x.myFavouriteFood.;.typeof, Array.isArray(), and isNaN() when debugging.
Index: 0 1 2
+--------+--------+--------+
Array | "Yam" |"Tomato"| "Milk" |
+--------+--------+--------+
| | |
V V V
items[0] items[1] items[2]
+---------------------------+
| student |
+---------------------------+
| name: "Ada" |
| age: 12 |
| class: "JSS2" |
| scores: [85, 90, 78] |
+---------------------------+
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.
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}`);
| Feature | Primitive | Object |
|---|---|---|
| Example | 42, "Ada", true | [1,2,3], { name: "Ada" } |
| Holds | One value | Many values |
| Copied by | Value | Reference |
| Mutable? | No (value is replaced) | Yes (contents can change) |
| Value | Meaning | Example |
|---|---|---|
undefined | No value yet | let x; |
null | Empty on purpose | let y = null; |
NaN | Failed math | "hi" * 2 |
| Feature | Array | Object |
|---|---|---|
| Syntax | [ ] | { } |
| Access | By index (0, 1, 2…) | By key (name, age…) |
| Best for | Lists of similar items | Related information |
| Example | ["Yam", "Tomato"] | { name: "Ada", age: 12 } |
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.
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!
Number("123").let arr = [1, 2, 3];arr[0] for the first item.let obj = { name: "Ada" };obj.name.Array.isArray(value).isNaN(value).Match the item on the left with its correct description on the right.
| Item | Description |
|---|---|
1. [1, 2, 3] | A. Object |
2. { name: "Ada" } | B. Array |
3. "hello" * 2 | C. NaN |
4. let x; | D. Undefined |
5. null | E. Empty on purpose |
Answers: 1-B, 2-A, 3-C, 4-D, 5-E
["Sword", "Shield"]. They pick up a potion. How do you add it?"15". How do you calculate their age next year?[85, 90, 78]. How do you find the average?{ name: "Ada", age: 12 }. How do you add a new property class: "JSS2"?“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!
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"; — Stringlet numberOfBooks = 5; — Numberlet hasLunch = true; — Booleanlet books = ["Maths", "English", "Science"]; — Arraylet owner = { name: "Ada", age: 12 }; — ObjectCreate 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.
fruits with 4 fruit names.push().pop().myPet with properties: name, type,
age, and isFriendly.typeof on each property and print the results.Number(), String(), and Boolean().[ ], index starts at 0, .length gives count.{ }, access with dot notation.typeof, Array.isArray(), and isNaN().undefined, null, and NaN?
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