Back

Activity 3.1 Defining and Invoking Functions

divider

Introduction

Introduction to Functions in JavaScript

Breaking Programs into Smaller, Reusable Parts

What Are Functions?

Functions (also called procedures) are blocks of code that perform a specific task.

They allow us to reuse logic, organize our programs, and simplify complex tasks.

Built-in Functions

You've already been using functions in your JavaScript programs.

console.log("Hello world!");

You may not know exactly how console.log() works behind the scenes, but that's okay. Functions are designed so you can use functionality without needing to understand every detail.

This is known as abstraction.

Key Benefits of Using Functions

  • Reusability: Write code once and use it multiple times.
  • Modularity: Break down complex problems into smaller, manageable parts.
  • Readability: Make code easier to understand and maintain.
  • Debugging: Find and fix errors in isolated sections.

Parts of a Function

function greeting() {
console.log("Hey buddy!");
console.log("How are you?");
}

First line (definition): Declares the function using the function keyword, its name, and parentheses for parameters.

Parts of a Function

function greeting() {
console.log("Hey buddy!");
console.log("How are you?");
}

Definition line: Includes the function keyword, the function name, and parameters (if any).

Body: Contains the instructions that run when the function is called.

Function Definition Line

function greeting() {
console.log("Hey buddy!");
console.log("How are you?");
}

In this example:

  • function - keyword that starts a function definition.
  • greeting - the function name.
  • () - parentheses (empty for now, later used for parameters).

Defining a Function ≠ Calling a Function

Defining a function describes what it does, but it doesn't run until you call or invoke it.

function greeting() {
console.log("Hey buddy!");
console.log("How are you?");
}
greeting(); // Function call
greeting(); // Call it again

Each time greeting() is called, the same code runs again — a simple example of code reuse.

Variable Scope

Variables declared inside a function exist only within that function.

function randomNumber() {
let randomNumber = Math.floor(Math.random() * 10);
}
function revealAnswer() {
console.log("The secret number was " + randomNumber);
}

Local Variables: Declared inside a function — only accessible there.

Once a function finishes running, its local variables are removed from memory.

Functions in Practice

  • Keep your overall program logic short and easy to read.
  • Group related behavior into its own function.

Next Lesson Preview

Parameters and Return Values

So far, our functions don't take any input or return any output.

In the next lesson, you'll learn how to make your functions more flexible by:

  • Passing arguments into a function.
  • Returning values back to the caller.

Key Terms

Function
A named block of code that performs a specific task. Functions make programs modular, reusable, and easier to read.
Function Definition
The line that starts a function and the code block that follows it. It specifies the function name and its parameters (if any).
Function Body
The code block inside curly braces that contains the instructions the function will execute.

Key Terms

Return Value
The value a function sends back to the part of the program that called it. (In this lesson, our functions do not return values.)
Function Call (Invocation)
The statement that executes a function by using its name followed by parentheses. i.e. "Using the function".
Local Variable
A variable declared inside a function. It can only be accessed within that function and is removed from memory once the function finishes.

Key Terms

Scope
The region of a program where a variable can be accessed. Local variables have function-level scope.
Abstraction
The concept of using functions or other structures without knowing the full details of how they work internally.
Modularity
Dividing a program into independent sections or modules, such as functions, to simplify design and debugging.

Key Terms

Code Reuse
The practice of writing a function once and using it multiple times instead of duplicating code.

'F' → Fullscreen

Objectives

  • icon Define and invoke simple functions in JavaScript.
  • icon Explain how functions improve readability and organization.
  • icon Use functions to structure a simple console-based program.
divider

Activity Tasks

  • icon Create a new JavaScript file named 3-1-functions.js.
  • icon Complete each task individually and run your program to verify the output.

Task 1: Create and Call Functions

  • icon Define three functions: showIntro(), displayMenu(), and gameOver().
  • icon Each function should print a short message related to its name.
  • icon At the bottom of your file, call these functions in sequence to test them.
main.js
function showIntro() {
console.log("--- MINI GAME COLLECTION VOL. 1 ---");
console.log("Welcome!");
console.log();
}
function displayMenu() {
console.log("1. Guess the Number");
console.log("2. Lucky Dice");
console.log("3. Spin the Wheel");
console.log("4. Exit");
console.log();
}
function gameOver() {
console.log("Thanks for playing!");
console.log("Goodbye!");
}
// Call your functions here:
showIntro();
displayMenu();
// Later, you'll decide where to call gameOver()

Task 2: Menu System

  • icon Implement the main menu system using a while loop and if / else if / else statements. The mini-game functions will be implemented in the next task.
main.js
function showIntro() {
3 collapsed lines
console.log("-- MINI GAME COLLECTION VOL. 1 --");
console.log("Welcome!");
console.log();
}
function displayMenu() {
5 collapsed lines
console.log("1. Guess the Number");
console.log("2. Lucky Dice");
console.log("3. Spin the Wheel");
console.log("4. Exit");
console.log();
}
function gameOver() {
2 collapsed lines
console.log("Thanks for playing!");
console.log("Goodbye!");
}
function playGuessTheNumber() {
// To Do: Guess the Number Mini-Game
}
function playLuckyDice() {
// To Do: Lucky Dice Mini-Game
}
function playSpinTheWheel() {
// To Do: Spin the Wheel Mini-Game
}
let choice = "";
showIntro();
while (choice !== "4") {
displayMenu();
choice = prompt("Choose mini-game: ");
if (choice == "1") {
playGuessTheNumber();
}
else if (choice == "2") {
playLuckyDice();
}
else if (choice == "3") {
playSpinTheWheel();
}
else if (choice == "4") {
gameOver();
}
else {
console.log("Invalid choice.");
}
console.log();
}

Task 3: Implement Mini-Games

  • icon The Number Guessing mini-game has been implemented for you.
  • icon Implement the remaining mini-game functions. They don't need to be complex, but have some fun!
main.js
function showIntro() {
3 collapsed lines
console.log("-- MINI GAME COLLECTION VOL. 1 --");
console.log("Welcome!");
console.log();
}
function displayMenu() {
5 collapsed lines
console.log("1. Guess the Number");
console.log("2. Lucky Dice");
console.log("3. Spin the Wheel");
console.log("4. Exit");
console.log();
}
function gameOver() {
2 collapsed lines
console.log("Thanks for playing!");
console.log("Goodbye!");
}
function playGuessTheNumber() {
console.log("--- Guess the Number ---");
let secret = Math.floor(Math.random() * 10) + 1;
let guessText = prompt("Guess my secret number between 1 and 10: ");
let guess = Number(guessText);
console.log("It was " + secret + "!");
if (guess == secret)
console.log("You Win!");
else
console.log("You Lose!");
}
function playLuckyDice() {
console.log("--- Lucky Dice ---");
console.log();
let betText = prompt("Bet on a total between 2 and 12: ");
let bet = Number(betText);
let die1 = Math.floor(Math.random() * 6) + 1;
let die2 = Math.floor(Math.random() * 6) + 1;
let total = die1 + die2;
console.log("You rolled " + die1 + " and " + die2 + " (total: " + total + ").");
if (total == bet)
console.log("You Win!");
else
console.log("You Lose!");
}
function playSpinTheWheel() {
console.log("--- Spin the Wheel ---");
console.log();
let betText = prompt("Pick a number on the wheel between 1 and 25: ");
let bet = Number(betText);
let wheel = Math.floor(Math.random() * 25) + 1;
console.log("The wheel landed on " + wheel + ".");
if (wheel == bet)
console.log("You Win!");
else
console.log("You Lose!");
}
26 collapsed lines
let choice = "";
showIntro();
while (choice !== "4") {
displayMenu();
choice = prompt("Choose mini-game: ");
if (choice == "1") {
playGuessTheNumber();
}
else if (choice == "2") {
playLuckyDice();
}
else if (choice == "3") {
playSpinTheWheel();
}
else if (choice == "4") {
gameOver();
}
else {
console.log("Invalid choice.");
}
console.log();
}
divider

Sample Output

Your program output should look similar to the sample output below.

Sample Output
-- MINI GAME COLLECTION VOL. 1 --
Welcome!
1. Guess the Number
2. Lucky Dice
3. Spin the Wheel
4. Exit
Choose mini-game: 1
--- Guess the Number ---
Guess my secret number betwen 1 and 10: 7
It was 7!
You Win!
1. Guess the Number
2. Lucky Dice
3. Spin the Wheel
4. Exit
Choose mini-game: 4
Thanks for playing!
Goodbye!
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. What is the purpose of defining a function instead of placing all code in one big block?
  2. How does invoking a function help you organize or reuse code?
  3. What patterns do you notice in how functions are defined and called?
divider

Submission

Submit your completed .js file and reflection answers to the appropriate dropbox.

Activity Complete