Complete solution (100% reference)
index.html- Main HTML pagescript.js- JavaScript logicstyles.css- Styling and layoutpackage.json- Dependenciessetup.sh- Setup scriptREADME.md- Instructions (below)💡 Download the ZIP, extract it, and follow the instructions below to get started!
This is the INSTRUCTOR'S COMPLETE SOLUTION for W2 Activity 06: Functions. This solution demonstrates all 4 exercises with comprehensive teaching comments, common mistake documentation, and detailed instructor notes.
All Exercises Complete:
function name(params) { }+ operatorMath.random() and Math.floor()# Navigate to solution folder
cd "Paid Courses/W2 Advanced JavaScript Foundations/Template Solution/activity-06-functions"
# Run setup script
chmod +x setup.sh
./setup.sh
# Start the development server
npm start
The activity will:
Open index.html in any modern browser:
Learning Focus: Basic function syntax, parameters, return values
Functions Implemented:
addition(x, y) // Returns x + y
subtract(x, y) // Returns x - y
multiply(x, y) // Returns x * y
divide(x, y) // Returns x / y
Key Teaching Points:
+prompt()Test Cases:
| Input (x, y) | Addition | Subtraction | Multiplication | Division |
|---|---|---|---|---|
| 10, 5 | 15 | 5 | 50 | 2 |
| 20, 4 | 24 | 16 | 80 | 5 |
| 7.5, 2.5 | 10 | 5 | 18.75 | 3 |
| -10, 5 | -5 | -15 | -50 | -2 |
| 10, 0 | 10 | 10 | 0 | Infinity |
Common Student Mistakes:
return statement -> function returns undefinedLearning Focus: Global variables, onclick events, HTML-JS connection
Implementation:
var myWords = "Hello World"; // Global variable
function echo() { // No parameters
alert(myWords); // Accesses global
}
HTML Required:
<button onclick="echo()">Echo</button>
Key Teaching Points:
Expected Behavior:
echo() functionCommon Student Mistakes:
() in onclick: onclick="echo" -> doesn't call functionclick instead of onclickLearning Focus: Math.random(), number generation, pure randomness
Implementation:
function random() {
var diceRoll = Math.floor(Math.random() * 6) + 1;
alert("🎲 You rolled: " + diceRoll);
}
HTML Required:
<button onclick="random()">Roll Dice 🎲</button>
Key Teaching Points:
Math.random() returns 0 to 0.999...Math.floor()Random Number Formula Breakdown:
Step 1: Math.random() → 0.0000 to 0.9999...
Step 2: Math.random() * 6 → 0.0000 to 5.9999...
Step 3: Math.floor(...) → 0, 1, 2, 3, 4, or 5
Step 4: ... + 1 → 1, 2, 3, 4, 5, or 6 ✅
Expected Behavior:
Common Student Mistakes:
+ 1 -> returns 0-5 instead of 1-6Math.round() -> can return 0 or 7Math.ceil() without understanding distributionVerification Test: Roll 60 times, should see all numbers 1-6 appear multiple times with roughly even distribution.
Learning Focus: Multi-function systems, state management, function composition
Global State:
var myMoney = 50; // Starting balance
Functions Implemented:
order(food) // Routes food to payment system
balance(price) // Calculates remaining money (pure function)
pay(food, price) // Processes transaction, updates state
Menu Items:
HTML Required:
<button onclick="order('Chicken Chop')">Chicken Chop RM12</button>
<button onclick="order('Fish and Chips')">Fish and Chips RM14</button>
<button onclick="order('Pasta')">Pasta RM16</button>
System Architecture:
User clicks button
↓
order(food) determines price
↓
pay(food, price) checks balance
↓
balance(price) calculates remaining money
↓
If affordable: Update myMoney, log success
If not: Keep myMoney same, log error
Key Teaching Points:
balance) vs impure (pay)===Transaction Flow Example:
Starting balance: RM50
Transaction 1: Order Chicken Chop (RM12)
order("Chicken Chop") calledpay("Chicken Chop", 12)balance(12) returns 38myMoney = 38Transaction 2: Order Fish and Chips (RM14)
pay("Fish and Chips", 14)balance(14) returns 24myMoney = 24Transaction 3: Order Pasta (RM16)
pay("Pasta", 16)balance(16) returns 8myMoney = 8Transaction 4: Order Chicken Chop (RM12) - FAILS
pay("Chicken Chop", 12)balance(12) returns -4myMoney stays 8 (unchanged)Common Student Mistakes:
myMoney after purchase -> infinite money glitchbalance(price) > 0 instead of >= 0"chicken chop" vs "Chicken Chop"pay() function= (assignment) instead of === (comparison)Problem: Students mix up syntax from different languages
// ❌ WRONG - Python syntax
def addition(x, y):
return x + y
// ✅ CORRECT - JavaScript syntax
function addition(x, y) {
return x + y;
}
Problem: Calculating but not returning
// ❌ WRONG
function addition(x, y) {
x + y; // Calculates but doesn't return
}
console.log(addition(5, 3)); // undefined
// ✅ CORRECT
function addition(x, y) {
return x + y; // Returns the result
}
console.log(addition(5, 3)); // 8
Problem: prompt() returns string, not number
// ❌ WRONG
var x = prompt("Number:"); // "5" (string)
var y = prompt("Number:"); // "3" (string)
console.log(addition(x, y)); // "53" (concatenation!)
// ✅ CORRECT - Method 1
var x = Number(prompt("Number:")); // 5 (number)
var y = Number(prompt("Number:")); // 3 (number)
// ✅ CORRECT - Method 2 (shorthand)
var x = +prompt("Number:"); // 5 (number)
var y = +prompt("Number:"); // 3 (number)
console.log(addition(x, y)); // 8 (addition!)
Problem: Missing parentheses or quote issues
<!-- ❌ WRONG - Missing () -->
<button onclick="echo">Echo</button>
<!-- ❌ WRONG - Quote mismatch -->
<button onclick="order("Pasta")">Pasta</button>
<!-- ✅ CORRECT -->
<button onclick="echo()">Echo</button>
<!-- ✅ CORRECT - Single quotes inside double -->
<button onclick="order('Pasta')">Pasta</button>
Problem: Variables declared in wrong scope
// ❌ WRONG - Variable is local, not global
function echo() {
var myWords = "Hello"; // Only exists inside function
alert(myWords);
}
// myWords is not accessible outside echo()
// ✅ CORRECT - Variable is global
var myWords = "Hello"; // Exists everywhere
function echo() {
alert(myWords); // Can access global
}
Recommended Flow:
Exercise 4 Breakdown:
myMoney and balance() functionpay() function with simple logicorder() function with one menu item// RETURN - Gives value back (can use it)
function add(a, b) {
return a + b;
}
var sum = add(5, 3); // sum = 8, can use it!
// CONSOLE.LOG - Just displays (can't use)
function add(a, b) {
console.log(a + b);
}
var sum = add(5, 3); // sum = undefined, can't use!
// PURE - No side effects, same input = same output
function balance(price) {
return myMoney - price; // Doesn't change myMoney
}
// IMPURE - Modifies state, has side effects
function pay(food, price) {
myMoney = balance(price); // Changes myMoney
console.log("Paid!"); // Side effect (logging)
}
activity-06-functions/
├── index.html # HTML with buttons for Exercises 2, 3, 4
├── script.js # Complete solution with teaching comments
├── package.json # Project dependencies
├── setup.sh # Setup automation script
└── README.md # This file (instructor guide)
Each section includes:
Add more operations to Exercise One:
function modulo(x, y) {
return x % y; // Remainder after division
}
function power(x, y) {
return Math.pow(x, y); // x to the power of y
}
function squareRoot(x) {
return Math.sqrt(x); // Square root of x
}
HTML:
<button onclick="console.log(modulo(x, y))">Modulo</button>
<button onclick="console.log(power(x, y))">Power</button>
<button onclick="console.log(squareRoot(x))">√ of X</button>
Create different dice types:
function rollD4() {
return Math.floor(Math.random() * 4) + 1; // 1-4
}
function rollD8() {
return Math.floor(Math.random() * 8) + 1; // 1-8
}
function rollD20() {
return Math.floor(Math.random() * 20) + 1; // 1-20
}
function rollMultiple(numDice, sides) {
var total = 0;
for (var i = 0; i < numDice; i++) {
total += Math.floor(Math.random() * sides) + 1;
}
return total;
}
// Roll 2d6 (two 6-sided dice)
alert("2d6: " + rollMultiple(2, 6));
Add more features to the restaurant:
// Add money function
function addMoney(amount) {
myMoney += amount;
console.log("Added RM" + amount + ". New balance: RM" + myMoney);
}
// Order history tracking
var orderHistory = [];
function pay(food, price) {
if (balance(price) >= 0) {
myMoney = balance(price);
orderHistory.push(food);
console.log("Order history: " + orderHistory.join(", "));
console.log("Total items ordered: " + orderHistory.length);
}
}
// Tax calculation
function calculateTax(price) {
return price * 0.06; // 6% tax
}
function payWithTax(food, price) {
var tax = calculateTax(price);
var total = price + tax;
if (balance(total) >= 0) {
myMoney = balance(total);
console.log("Food: RM" + price + ", Tax: RM" + tax.toFixed(2) +
", Total: RM" + total.toFixed(2));
}
}
Use Unicode dice faces:
var diceFaces = {
1: "⚀",
2: "⚁",
3: "⚂",
4: "⚃",
5: "⚄",
6: "⚅"
};
function randomVisual() {
var roll = Math.floor(Math.random() * 6) + 1;
alert("You rolled: " + diceFaces[roll] + " (" + roll + ")");
}
Combine all concepts into a mini-game:
// Game state
var playerMoney = 100;
var playerInventory = [];
var rollCount = 0;
// Shop menu
var shopItems = {
"Health Potion": 10,
"Magic Scroll": 15,
"Lucky Charm": 20
};
// Purchase item
function buyItem(item) {
var price = shopItems[item];
if (playerMoney >= price) {
playerMoney -= price;
playerInventory.push(item);
console.log("Bought " + item + "! Remaining: $" + playerMoney);
} else {
console.log("Not enough money!");
}
}
// Roll for loot
function rollForLoot() {
rollCount++;
var loot = Math.floor(Math.random() * 20) + 1;
playerMoney += loot;
console.log("Roll #" + rollCount + ": Found $" + loot +
" (Total: $" + playerMoney + ")");
}
// Show stats
function showStats() {
console.log("=== PLAYER STATS ===");
console.log("Money: $" + playerMoney);
console.log("Items: " + (playerInventory.length || "None"));
console.log("Rolls: " + rollCount);
}
addition(x, y) returns x + ysubtract(x, y) returns x - ymultiply(x, y) returns x * ydivide(x, y) returns x / y+ conversion (4 pts)myWords declared (5 pts)echo() function works correctly (8 pts)random() function declared (5 pts)Math.random() formula (1-6) (10 pts)myMoney global variable initialized to 50 (3 pts)order(food) function with if/else logic (7 pts)balance(price) calculation function (5 pts)pay(food, price) transaction logic (10 pts)
myMoney when successfulTotal: 100 points
Exercise 1 (25 pts):
Exercise 2 (20 pts):
Exercise 3 (20 pts):
Exercise 4 (30 pts):
Symptoms:
Debugging Steps:
script.js is linked in index.htmlCommon Causes:
<script src="script.js"></script> in HTMLecho() in JS but eko() in HTML<head> instead of before </body>Symptoms:
NaN instead of numbersDebugging Steps:
// Add these logs to debug
console.log("x:", x, "Type:", typeof x);
console.log("y:", y, "Type:", typeof y);
Solution:
Ensure + conversion before prompt:
// ❌ WRONG
var x = prompt("Number:"); // Returns string
// ✅ CORRECT
var x = +prompt("Number:"); // Converts to number
Symptoms:
Debugging Steps:
function random() {
var step1 = Math.random();
var step2 = step1 * 6;
var step3 = Math.floor(step2);
var step4 = step3 + 1;
console.log("Steps:", step1, step2, step3, step4);
alert(step4);
}
Common Causes:
+ 1: Math.floor(Math.random() * 6) -> 0-5Math.round: Can return 0 or 7Math.floor(Math.random()) * 6 + 1Solution:
var diceRoll = Math.floor(Math.random() * 6) + 1; // 1-6
Symptoms:
myMoney stays at 50Debugging Steps:
function pay(food, price) {
console.log("Before:", myMoney);
if (balance(price) >= 0) {
myMoney = balance(price);
console.log("After:", myMoney); // Should be different!
}
}
Common Cause:
Missing the myMoney = balance(price); update line
Solution:
function pay(food, price) {
if (balance(price) >= 0) {
myMoney = balance(price); // MUST UPDATE!
console.log("You have ordered the " + food);
}
}
Symptoms:
Debugging Steps:
console.log("Price:", price);
console.log("Balance:", balance(price));
console.log("Check:", balance(price) < 0);
Common Causes:
> instead of >=> 0 instead of < 0&& instead of condition checkSolution:
if (balance(price) < 0) { // If WOULD BE negative
console.log("No money"); // Reject
} else { // If >= 0
myMoney = balance(price); // Accept
}
Use this checklist when reviewing student submissions:
x, y)return statement+, -, *, /+prompt() or Number(prompt())x and y (or similar)console.log()myWords declared as global variable (outside functions)myWords initialized to "Hello World"echo() function declaredecho() uses alert() to displayecho() accesses global myWords variable(): onclick="echo()"random() function declaredMath.random()Math.floor()Math.floor(Math.random() * 6) + 1alert()myMoney global variable initialized to 50balance(price) function declaredbalance() returns myMoney - pricepay(food, price) function declaredpay() checks if balance(price) < 0pay() updates myMoney when affordablepay() shows error message when not affordableorder(food) function declaredorder() has if/else if for all 3 foodsorder() calls pay() with correct argumentsExercise One:
addition)Exercise 2:
echo() should workExercise 3:
Math.random() with console testsExercise 4:
myMoney and balance()pay() with simple logicorder() with one itemQ: "Do parameters have to be named x and y?"
A: No! They can be any valid variable name. We use x and y for simplicity, but num1 and num2 or first and second work too. Just be consistent inside the function body.
Q: "What's the difference between parameters and arguments?"
A: Parameters are the placeholders in the function definition (function add(x, y)). Arguments are the actual values you pass when calling (add(5, 3)). Think: parameters = variables, arguments = values.
Q: "Why do we need return?"
A: return gives the value back so you can use it! Without return, the function calculates but you can't save or use the result. console.log just displays, return gives back.
Q: "Can I use const/let instead of var?"
A: Yes! In modern JavaScript, const and let are preferred. But for W2 beginner level, we use var for simplicity. Discuss scope differences if students ask.
Q: "Why + before prompt()?"
A: The + is shorthand for converting to number. prompt() always returns a string. +prompt() converts "5" to 5. Alternative: Number(prompt()).
Q: "My dice shows decimals, not integers!"
A: You're missing Math.floor(). Math.random() * 6 + 1 gives 1.0 to 6.999. Math.floor(Math.random() * 6) + 1 gives integers 1-6.
Q: "The restaurant lets me buy infinitely!"
A: You forgot to update myMoney inside the pay() function. After checking affordability, add: myMoney = balance(price);
Q: "onclick doesn't work, button does nothing!" A: Check these:
() after function name? onclick="echo()" not "echo"echo() in JS and echo() in HTMLorder('Pasta') with single quotes inside doubleTeach students this systematic approach:
console.log(typeof variable))For Struggling Students:
For Advanced Students:
const, let, =>)This solution is part of the Telebort W2 Advanced JavaScript Foundations course.
Copyright: Telebort Engineering Course: W2 Advanced JavaScript Foundations Activity: 06 - Functions Version: One.0.0 Last Updated: October 2024
Need Help? Contact the teaching team or check the course forum for additional support.