Lab: Exploring Functions in JavaScript
Objectives:
1. Understand the concept of functions in JavaScript.
2. Learn how to define, call, and work with different types of functions.
3. Explore parameters, return values, and different scopes in functions.
4. Apply functions to solve real-world problems using Ugandan examples.
Part 1: Introduction to Functions
What is a Function?
A function is a block of code designed to perform a particular task. You can call it when needed
to avoid repetitive code. Functions allow for more modular and maintainable code.
Syntax of a JavaScript Function
function functionName(parameters) {
// Code block
return value; // Optional
}
Example 1: A Simple Greeting Function
Define a function that greets someone in Uganda:
function greetUgandan(name) {
console.log(`Hello ${name}, welcome to Uganda!`);
}
greetUgandan("John");
Task 1:
Create a function greetStudent that accepts a student's name and prints a message:
Hello [name], you are attending the JavaScript class!
Part 2: Functions with Parameters
A function can accept parameters (arguments) to work with dynamic inputs. Let’s calculate the
total cost of a taxi ride in Kampala.
Example 2: Calculate Taxi Fare
function calculateTaxiFare(distance, farePerKm) {
return distance * farePerKm;
}
let distanceToWandegeya = 10; // Distance in kilometers
let farePerKm = 5000; // UGX
let totalFare = calculateTaxiFare(distanceToWandegeya, farePerKm);
console.log(`Total taxi fare to Wandegeya is UGX ${totalFare}`);
Task 2:
Create a function calculateFoodExpense that takes the number of meals and cost per meal,
returning the total food expense.
Part 3: Functions with Return Values
Functions can return a value that can be used elsewhere in the program. This makes functions
versatile for calculations.
Example 3: Calculating the Average Score of Students
Imagine you are marking exams in a Ugandan school and need to calculate the average score.
function calculateAverage(scores) {
let total = 0;
for (let i = 0; i < scores.length; i++) {
total += scores[i];
}
return total / scores.length;
}
let studentScores = [85, 78, 92, 67, 88];
let averageScore = calculateAverage(studentScores);
console.log(`The average score is ${averageScore}`);
Task 3:
Write a function calculateWaterUsage that calculates the average daily water usage for a
household in Kampala over a week.
Part 4: Anonymous and Arrow Functions (ADVANCED)
In JavaScript, you can create anonymous functions (functions without names) and arrow
functions (concise syntax).
Anonymous Function Example:
let greet = function(name) {
console.log(`Hello ${name}, how is Uganda treating you?`);
};
greet("Paul");
Arrow Function Example:
let greet = (name) => {
console.log(`Hello ${name}, welcome to the JavaScript world!`);
};
greet("Paul");
Task 4:
Create an arrow function calculateArea that takes in the length and width of a plot of land (in
meters) in Kampala and returns the area.
Part 5: Functions with Multiple Parameters
You can pass multiple arguments to functions to handle more complex operations. For instance,
let’s help a farmer calculate the total revenue from selling matooke.
Example 5: Calculate Revenue for a Farmer
function calculateRevenue(pricePerBunch, numberOfBunches) {
return pricePerBunch * numberOfBunches;
}
let pricePerBunch = 15000; // UGX
let bunchesSold = 30; // Number of bunches sold
let revenue = calculateRevenue(pricePerBunch, bunchesSold);
console.log(`Total revenue for selling matooke is UGX ${revenue}`);
Task 5:
Write a function calculateProfit that accepts the selling price, cost price, and number of
units sold, and returns the profit for a small business selling products like maize flour.
Part 6: Functions with Default Parameters (ADVANCED)
JavaScript allows you to assign default values to function parameters. If no argument is
provided, the default value is used.
Example 6: Calculate School Fees with Default Boarding Fee
function calculateFees(tuitionFee, boardingFee = 500000) {
return tuitionFee + boardingFee;
}
let totalFeesWithBoarding = calculateFees(1500000);
console.log(`Total school fees (with boarding) are UGX
${totalFeesWithBoarding}`);
let totalFeesWithoutBoarding = calculateFees(1500000, 0);
console.log(`Total school fees (without boarding) are UGX
${totalFeesWithoutBoarding}`);
Task 6:
Write a function calculateInternetCost where the default value for a data bundle is UGX
50,000. The function should calculate the total cost for a given number of bundles.
Part 7: Recursive Functions (ADVANCED)
A recursive function is a function that calls itself to solve a smaller instance of the same
problem.
Example 7: Calculate Factorial (Recursive)
function factorial(n) {
if (n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
let result = factorial(5);
console.log(`The factorial of 5 is ${result}`);
Task 7:
Create a recursive function countdown that prints a countdown from a given number to 0.
Part 8: Function Scope
Scope refers to the visibility or accessibility of variables inside a function. Variables defined
inside a function are local to that function and cannot be accessed outside it.
Example 8: Local and Global Scope
let globalVar = "I'm a global variable";
function testScope() {
let localVar = "I'm a local variable";
console.log(globalVar); // Accessible inside the function
console.log(localVar); // Accessible inside the function
}
testScope();
console.log(globalVar); // Accessible outside the function
// console.log(localVar); // Error: localVar is not defined
Task 8:
Write a function that demonstrates the difference between local and global variables. Use an
example where a global variable represents a national statistic in Uganda.
Part 9: IIFE (Immediately Invoked Function Expression) (ADVANCED)
An IIFE is a function that runs as soon as it is defined.
Example 9: Using IIFE
(function () {
console.log("This function runs immediately!");
})();
Task 9:
Create an IIFE that prints the message: "Welcome to JavaScript in Uganda!"
Part 10: Higher-Order Functions (ADVANCED)
A higher-order function is a function that takes another function as an argument or returns a
function as a result.
Example 10: Higher-Order Function with a Callback
function processPayment(amount, paymentCallback) {
console.log(`Processing payment of UGX ${amount}`);
paymentCallback();
}
function onPaymentSuccess() {
console.log("Payment successful!");
}
processPayment(50000, onPaymentSuccess);
Task 10:
Create a higher-order function fetchData that simulates fetching data from a server. It should
accept a callback function that displays a message like "Data successfully retrieved from the
server."
Part 11: Applying Functions to Real-World Problems
Scenario: You are developing an application for a boda-boda rider to calculate the total income
from daily trips in Kampala. The rider earns UGX 2,000 per kilometer. Write a function
calculateIncome that takes the number of kilometers traveled per day and returns the total
income for the day.
function calculateIncome(kilometers) {
let incomePerKm = 2000;
return kilometers * incomePerKm;
}
let kilometersTraveled = 50; // Kilometers traveled in a day
let dailyIncome = calculateIncome(kilometersTraveled);
console.log(`The total income for the day is UGX ${dailyIncome}`);
Task 11:
Extend the calculateIncome function to include bonuses for trips during rush hour.
Lab Summary:
In this lab, we covered:
● Defining, calling, and working with various types of functions.
● Parameters, return values, and scopes in JavaScript.
● Recursive functions, higher-order functions, and IIFE.
● Applying functions to real-world.
By the end of this lab, you should have a strong understanding of how to create and use
functions to solve problems effectively in JavaScript.
Additional Exercises:
1. Write a function that calculates the total electricity bill for a household in Kampala based
on the number of units consumed.
2. Create a function to determine if a Ugandan year is a leap year.
3. Write a function that calculates the total boda-boda fare for a journey between two
Ugandan towns based on distance and per kilometer fare.