Intermediate Level • Lesson 3

🔄 Functions and Scope

⏱️ 45 minutes 📚 Intermediate 🎯 Reusable Code
🔧

Build Reusable Code!

Functions are like recipes - write once, use many times!

What are Functions?

Functions are reusable blocks of code that perform specific tasks. Think of them like recipes - once you write the recipe, you can cook that dish anytime without rewriting the instructions!

Functions help us organize code, avoid repetition, and make programs easier to understand and maintain.

💡 Real Life Example: A vending machine is like a function - you input money and a selection, it processes your request, and returns your snack!

Key Concepts

📝

Declaration

Creating a function with the 'function' keyword and a name.

📞

Calling

Running a function by using its name followed by ().

📥

Parameters

Input values that functions receive to work with.

📤

Return Value

The output that a function sends back after processing.

🎯

Scope

Where variables can be accessed - inside or outside functions.

🧩

Modular Code

Breaking programs into small, reusable function pieces.

Anatomy of a Function

Function Structure:

function greetStudent(name) { let message = "Hello, " + name + "!"; return message; } // Calling the function let greeting = greetStudent("Ahmad"); console.log(greeting); // Hello, Ahmad!

Parts of a Function:

  • function - keyword to create a function
  • greetStudent - function name (use camelCase)
  • (name) - parameter (input)
  • { } - curly braces contain the function code
  • return - sends back the result

Simple Function Example

🎵 Greeting Function

function sayHello() { console.log("Selamat pagi!"); console.log("Welcome to class!"); } // Call the function sayHello(); // Call it again - reusable! sayHello();

Output:

Selamat pagi!
Welcome to class!
Selamat pagi!
Welcome to class!
              

Functions with Parameters

🧮 Calculator Function

function addNumbers(num1, num2) { let sum = num1 + num2; return sum; } // Using the function let result1 = addNumbers(5, 3); console.log(result1); // 8 let result2 = addNumbers(10, 20); console.log(result2); // 30

Parameters vs Arguments:

  • Parameters: Variables in function definition (num1, num2)
  • Arguments: Actual values when calling (5, 3)

Return Values

💰 Price Calculator with Return

function calculateTotal(price, quantity) { let total = price * quantity; return total; } let rotiCanaiTotal = calculateTotal(1.50, 5); console.log("Roti Canai: RM" + rotiCanaiTotal); // RM7.5 let tehTarikTotal = calculateTotal(2.50, 3); console.log("Teh Tarik: RM" + tehTarikTotal); // RM7.5

Important: return sends the value back. Without return, the function returns undefined!

Practical Example: Milo Recipe Function

🥤 Make Milo Function

function makeMilo(scoops, sugar, iceOrHot) { let recipe = "Milo Recipe:\n"; recipe = recipe + "- Add " + scoops + " scoops of Milo\n"; recipe = recipe + "- Add " + sugar + " spoons of sugar\n"; recipe = recipe + "- Pour " + iceOrHot + " water\n"; recipe = recipe + "- Stir well and enjoy!"; return recipe; } // Make different versions let myMilo = makeMilo(3, 2, "hot"); console.log(myMilo); let icedMilo = makeMilo(4, 1, "cold"); console.log(icedMilo);

Variable Scope

🎯 Understanding Scope

let globalScore = 100; // Global variable - accessible everywhere function playGame() { let localScore = 50; // Local variable - only inside function globalScore = globalScore + 10; // Can access global variable console.log("Local: " + localScore); console.log("Global: " + globalScore); } playGame(); console.log(globalScore); // Works - 110 // console.log(localScore); // Error! localScore doesn't exist here

Rule: Variables created inside functions stay inside. Variables outside are accessible everywhere!

Malaysian Greeting Generator

🌏 Multi-Language Greetings

function greetInLanguage(name, language) { let greeting; if (language === "malay") { greeting = "Selamat pagi, " + name + "!"; } else if (language === "chinese") { greeting = "早上好, " + name + "!"; } else if (language === "tamil") { greeting = "வணக்கம், " + name + "!"; } else { greeting = "Good morning, " + name + "!"; } return greeting; } console.log(greetInLanguage("Ahmad", "malay")); console.log(greetInLanguage("Wei Ming", "chinese")); console.log(greetInLanguage("Sarah", "english"));

Common Mistakes to Avoid

⚠️ Watch Out For:

  • Forgetting (): greetStudent vs greetStudent() - need () to call!
  • Wrong parameter count: Match the number of arguments to parameters
  • Forgetting return: If you need a value, use return!
  • Scope confusion: Variables inside functions can't be used outside

Summary

You've learned:

  • ✅ Functions are reusable blocks of code
  • ✅ Parameters pass information into functions
  • ✅ Return values send results back to where they were called
  • ✅ Scope determines where variables can be accessed
  • ✅ Modules organize code into smaller, manageable pieces
  • ✅ Reusing code makes programs easier to build and maintain

🎮 Interactive Challenge: Build Your Functions!

Open your browser console and try these exercises:

📝 Challenge 1: Simple Greeting

Create a function that greets by name:

function greet(name) { return "Hello, " + name + "!"; } // Test it console.log(greet("Your Name")); console.log(greet("Your Friend"));

🧮 Challenge 2: Math Helper

Create a multiplication function:

function multiply(a, b) { return a * b; } // Test with different numbers console.log(multiply(5, 3)); console.log(multiply(7, 8)); console.log(multiply(12, 4));

🍜 Challenge 3: Food Order Function

Create a function that takes an order:

function orderFood(foodName, quantity, price) { let total = quantity * price; let message = quantity + "x " + foodName + " = RM" + total; return message; } console.log(orderFood("Nasi Lemak", 2, 5.50)); console.log(orderFood("Roti Canai", 3, 1.50));
💡 Pro Tip: Test your functions with different inputs to make sure they work correctly!

🎯 Offline Activity: Function Recipe Cards

What You'll Do:

Create "recipe cards" for different functions, just like cooking recipes!

Instructions:

  1. Take 5 index cards or pieces of paper
  2. For each card, design a function for a common task
  3. Write the function name, parameters it needs, and what it returns
  4. Draw the flow: Input → Process → Output
  5. Share your function cards with classmates!

Example Function Card:

Function: calculateBMI

Purpose: Calculate Body Mass Index

Inputs (Parameters):

  • weight (in kg)
  • height (in meters)

Process: BMI = weight / (height × height)

Output (Return): BMI number

function calculateBMI(weight, height) { let bmi = weight / (height * height); return bmi; }

Ideas for Your Function Cards:

  • Convert Celsius to Fahrenheit
  • Calculate age from birth year
  • Find area of a rectangle
  • Convert RM to USD
  • Calculate discount price
🏆 Bonus Challenge: Write one function that calls another function inside it!

💪 Practice Challenges

Challenge 1: Temperature Converter

Create a function to convert Celsius to Fahrenheit:

function celsiusToFahrenheit(celsius) { // Formula: (C × 9/5) + 32 // Complete the function! } // Test it console.log(celsiusToFahrenheit(0)); // Should be 32 console.log(celsiusToFahrenheit(30)); // Should be 86

Challenge 2: Shopping Cart Total

Create a function that calculates cart total with tax:

function calculateCartTotal(subtotal, taxRate) { // Calculate tax amount // Add to subtotal // Return total } // Test with RM100 and 6% tax console.log(calculateCartTotal(100, 0.06)); // Should be 106

Challenge 3: Malaysian Greeting Generator

Create a function that generates greetings based on time:

function getGreeting(name, timeOfDay) { // If morning: "Selamat pagi" // If afternoon: "Selamat tengahari" // If evening: "Selamat petang" // If night: "Selamat malam" // Return greeting + name } console.log(getGreeting("Ahmad", "morning"));

Challenge 4: Circle Calculator

Create a function to calculate circle area:

function calculateCircleArea(radius) { // Formula: π × r² // Use 3.14159 for π // Complete the function! } console.log(calculateCircleArea(5)); console.log(calculateCircleArea(10));

Challenge 5: Grade Calculator

Create a function that converts score to grade:

function getGrade(score) { // 80-100: A // 60-79: B // 40-59: C // 0-39: D // Return the grade letter } console.log(getGrade(85)); // Should return "A" console.log(getGrade(65)); // Should return "B"