Lab - Exploring Functions in JavaScript
Lab - Exploring Functions in JavaScript
Objectives:
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.
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:
A function can accept parameters (arguments) to work with dynamic inputs. Let’s calculate the
total cost of a taxi ride in Kampala.
Task 2:
Create a function calculateFoodExpense that takes the number of meals and cost per meal,
returning the total food expense.
Functions can return a value that can be used elsewhere in the program. This makes functions
versatile for calculations.
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.
In JavaScript, you can create anonymous functions (functions without names) and arrow
functions (concise syntax).
greet("Paul");
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.
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.
A recursive function is a function that calls itself to solve a smaller instance of the same
problem.
function factorial(n) {
if (n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
Task 7:
Create a recursive function countdown that prints a countdown from a given number to 0.
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.
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.
(function () {
console.log("This function runs immediately!");
})();
Task 9:
Create an IIFE that prints the message: "Welcome to JavaScript in Uganda!"
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."
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;
}
Task 11:
Extend the calculateIncome function to include bonuses for trips during rush hour.
Lab Summary:
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.