Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Variables and Data Types for Web · Lesson 5 of 5

Special Ways to Work With Data

📖 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.
5
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, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→