Intermediate Level • Lesson 2

📦 Variables and Data Types

⏱️ 40 minutes 📚 Intermediate 🎯 Data Management
📊

Master Data Types!

Learn how to store and work with different types of information in JavaScript!

What are Data Types?

Data types tell JavaScript what kind of information you're working with. Just like in real life, we handle text differently from numbers - you can't add "hello" and "world" mathematically!

JavaScript has several main data types that you'll use every day:

💡 Think of it this way: Data types are like categories - foods, numbers, yes/no answers. Each category has different rules!

Key Concepts

💬

String

Text data - words, sentences, any characters in quotes.

🔢

Number

Numeric values - whole numbers and decimals for math.

Boolean

True or false values - perfect for yes/no decisions!

📋

Array

Lists of items - store multiple values in one variable.

🏷️

camelCase

Naming convention: firstWordLowercase, nextWordsCapitalized

🔄

Type Conversion

Changing data from one type to another when needed.

String - Working with Text

💬 Text in JavaScript

let studentName = "Ahmad"; let greeting = 'Selamat pagi!'; let city = "Kuala Lumpur"; console.log(studentName); // Ahmad console.log(greeting + " " + studentName); // Selamat pagi! Ahmad

Important: Strings can use "double quotes" or 'single quotes' - just be consistent!

Number - Working with Math

🔢 Numbers in JavaScript

let age = 13; // Whole number let price = 15.50; // Decimal number let temperature = -5; // Negative number let total = price * 3; // Math with numbers console.log(total); // 46.5

Note: Numbers don't use quotes! Compare: "42" is text, 42 is a number.

Boolean - True or False

✅ Boolean Values

let isRaining = true; let hasHomework = false; let schoolOpen = true; console.log(isRaining); // true console.log(hasHomework); // false

Use cases: Booleans are perfect for tracking status, making decisions, and conditions!

Array - Lists of Items

📋 Storing Multiple Items

let fruits = ["rambutan", "mangosteen", "durian"]; let scores = [95, 87, 92, 78]; let mixed = ["Ahmad", 13, true, "Kuala Lumpur"]; console.log(fruits[0]); // rambutan (first item) console.log(scores[1]); // 87 (second item) console.log(fruits.length); // 3 (number of items)

Key facts: Arrays use [ ] brackets, items are separated by commas, counting starts at 0!

Variable Naming Rules (camelCase)

🏷️ Good Variable Names

// Good variable names (camelCase) let userName = "Siti"; let totalPrice = 50.00; let isStudentActive = true; let shoppingCartItems = ["book", "pen", "notebook"]; // Bad variable names - avoid these! let username = "Siti"; // Not camelCase let total_price = 50.00; // Use camelCase, not snake_case let x = true; // Not descriptive let 1student = "Ahmad"; // Can't start with number!

Rules: Start with lowercase, capitalize each new word, be descriptive, no spaces or special characters!

Type Conversion

🔄 Converting Between Types

// String to Number let textNumber = "42"; let realNumber = Number(textNumber); console.log(realNumber + 8); // 50 // Number to String let age = 13; let message = "I am " + String(age) + " years old"; console.log(message); // I am 13 years old // Be careful with automatic conversion! console.log("5" + 3); // "53" (string joining) console.log(Number("5") + 3); // 8 (number addition)

Practical Example: Currency Converter

💱 RM to USD Converter

let ringitAmount = 100; let exchangeRate = 0.21; // 1 RM = 0.21 USD let usdAmount = ringitAmount * exchangeRate; let message = "RM" + ringitAmount + " = $" + usdAmount + " USD"; console.log(message); // RM100 = $21 USD

Common Mistakes to Avoid

⚠️ Watch Out For:

  • Mixing types: "5" + 5 = "55" not 10!
  • Forgetting quotes: let name = Ahmad; is an error, needs "Ahmad"
  • Wrong array index: Arrays start at 0, not 1!
  • Bad variable names: Use camelCase, not spaces or special characters

Summary

You've learned:

  • ✅ Strings store text in quotes
  • ✅ Numbers store numeric values for math
  • ✅ Booleans are true or false values
  • ✅ Arrays store lists of items in [ ] brackets
  • ✅ Use camelCase for variable names
  • ✅ Type conversion changes data types when needed

🎮 Interactive Challenge: Play with Data Types!

Open your browser console and try these exercises:

📝 Challenge 1: Create Variables

Create variables for your personal information:

let myName = "Your Name"; let myAge = 13; let myCity = "Your City"; let myHobbies = ["hobby1", "hobby2", "hobby3"]; let isStudent = true; console.log("Name: " + myName); console.log("Age: " + myAge); console.log("Hobbies: " + myHobbies);

🍜 Challenge 2: Malaysian Food Menu

Create a menu with prices:

let nasiLemak = 5.50; let rotiCanai = 1.50; let tehTarik = 2.50; let miloIce = 3.00; // Calculate a meal combo let comboPrice = nasiLemak + tehTarik; console.log("Combo Price: RM" + comboPrice);

📊 Challenge 3: Shopping List

Create an array and practice accessing items:

let shoppingList = ["apples", "bread", "milk", "eggs", "cheese"]; console.log("First item: " + shoppingList[0]); console.log("Last item: " + shoppingList[4]); console.log("Total items: " + shoppingList.length);
💡 Pro Tip: Use typeof operator to check data type: console.log(typeof "hello");

🎯 Offline Activity: Data Type Detective

What You'll Do:

Identify and categorize different types of data in everyday life!

Instructions:

  1. Look around your classroom, home, or at your phone
  2. Find examples of each data type in real life
  3. Write them down with their JavaScript equivalents
  4. Share your findings with classmates

Examples to Find:

  • Strings: Names on books, signs, messages
  • Numbers: Prices, temperatures, scores, phone numbers
  • Booleans: Light switches (on/off), door status (open/closed)
  • Arrays: Contact lists, playlists, ingredient lists

Example Findings:

// From my phone let contactName = "Mom"; // String let unreadMessages = 5; // Number let wifiConnected = true; // Boolean let recentApps = ["WhatsApp", "YouTube", "Instagram"]; // Array
🏆 Bonus Challenge: Find 3 examples where the wrong data type would cause problems! (Like trying to multiply someone's name)

💪 Practice Challenges

Challenge 1: Food Calculator

Create variables and calculate the total cost:

let chickenRice = 6.50; let icedMilo = 3.00; let curryPuff = 1.50; // Calculate total and add 6% tax

Expected: Calculate subtotal, tax, and final total

Challenge 2: Student Profile

Create a complete student profile using all data types:

let studentName = ""; // Add your name let studentAge = 0; // Add your age let isPresent = true; // Are you in class? let favoriteSubjects = []; // List 3 subjects // Display all information

Challenge 3: Malaysian Cities Array

Create and manipulate an array:

let cities = ["Kuala Lumpur", "Penang", "Johor Bahru", "Malacca"]; // Display the first city // Display the last city // Display total number of cities // Add "Kota Kinabalu" to the list

Challenge 4: E-Wallet Balance

Simulate e-wallet transactions:

let walletBalance = 100.00; let coffeePrice = 5.50; let lunchPrice = 12.00; // Subtract purchases from balance // Display remaining balance with message

Challenge 5: Type Conversion Challenge

Fix this code by converting types correctly:

let userInput = "25"; // This is a string let bonus = 10; // This is a number // We want to add them: should be 35, not "2510" // Fix the code! let total = userInput + bonus; console.log(total);