HAP studying on his laptop

Station 4: Reusable Code with Functions

Building Code Factories

Welcome to Station 4! After learning about conditionals, I found myself writing the same temperature-checking code over and over. Check if energy is low, check if temperature is high, check if robot is ready... I was copying and pasting everywhere!

I asked Prof. Teeters, "Is there a way to write this code once and use it many times?"

She smiled and said, "HAP, think of a function like a factory machine. You put raw materials in (parameters), the machine does its work, and a finished product comes out (return value). The same machine can make different products depending on what you put in!"

That's when I learned about functions — reusable blocks of code that can take inputs and produce outputs.

Let me show you how to build your own code factories... 🟠

🔬 Try it yourself: Function Factory →

What You'll Learn at This Station

HAP's Discovery: I thought I had to write the same code every time I needed similar logic. Then I learned that functions let me name a block of code, give it inputs, and get outputs — so I can use it over and over with different values!

📥 Parameters (Inputs)

( )

Placeholders inside the parentheses that receive values when you call the function. They let one function work with many different values.

📤 Return Values (Outputs)

return

The return keyword sends a value back to wherever the function was called. Without it, you get undefined.

🔒 Scope (Boundaries)

{ }

Variables created inside a function stay inside. They can't be seen or used from outside — this prevents accidental conflicts.

HAP surrounded by tangled code with an 'oops' expression

HAP's Confession:

  • I forgot to use the return keyword — my function ran but gave me undefined instead of the result!
  • I tried to use a variable I created inside a function from outside — JavaScript said it wasn't defined because of scope.
  • I called my function without parentheses — I got the function code itself instead of running it!
  • I mixed up parameters and arguments — Prof. Teeters helped me remember: Parameters are Placeholders, Arguments are Actual values.

The Problem: Repeated Code

Before I learned functions, my Robot ID Card code looked like this — the same logic repeated for each value:

Without Functions — Repeated Code
// Check energy status
let energyStatus;
if (energyLevel > 75) {
    energyStatus = "High";
} else if (energyLevel > 25) {
    energyStatus = "Medium";
} else {
    energyStatus = "Low";
}

// Check temperature status (same pattern!)
let tempStatus;
if (coreTemperature > 75) {
    tempStatus = "High";
} else if (coreTemperature > 25) {
    tempStatus = "Medium";
} else {
    tempStatus = "Low";
}

// Check battery status (same pattern again!)
let batteryStatus;
if (backupBattery > 75) {
    batteryStatus = "High";
} else if (backupBattery > 25) {
    batteryStatus = "Medium";
} else {
    batteryStatus = "Low";
}

// I'm copying the same logic THREE times!

Every time I needed to classify a value, I copied and pasted the same code. If I wanted to change the thresholds, I'd have to change them in multiple places!

Anatomy of a Function

A function has four key parts: the function keyword, a name, parameters in parentheses, and a body with a return statement:

Function Structure
//  keyword  name      parameter (input)
//    ↓       ↓            ↓
   function getStatus(value) {
       // Body: the code that runs
       if (value > 75) {
           return "High";      // ← return sends back the result
       } else if (value > 25) {
           return "Medium";
       } else {
           return "Low";
       }
   }

// Now I can USE this function with different values:
let energyStatus = getStatus(energyLevel);        // "High", "Medium", or "Low"
let tempStatus = getStatus(coreTemperature);      // Same logic, different value!
let batteryStatus = getStatus(backupBattery);     // Reused again!

One function replaces three copies of the same code. If I need to change the thresholds, I only change them in one place!

1. Define Once

Write the function with function name(params) . This creates the "factory machine" but doesn't run it yet.

2. Call Many Times

Use name(arguments) to run the function. You can call it as many times as you need with different values.

3. Parameters Receive

Parameters are placeholder names. When you call getStatus(85), the value 85 becomes value inside the function.

4. Return Sends Back

The return statement sends a value back. Whatever you return becomes the result of calling the function.

🎬 Watch: Function Academy

View Transcript

HAP: Hey. It's Hap. And I just found out that JavaScript without functions would just be silly. So let me tell you what they are, how we write them, and how we use them. Imagine you need to do the same thing over and over.

HAP: Without functions, you'd copy and paste the same code everywhere. That's messy. And if you need to change it, you'd have to find every copy. But with a function, you write the code once, give it a name, and then just call that name whenever you need it. One place to write it.

HAP: One place to fix it. That's the power of functions. Every function has the same basic parts. Let's break them down. First, the keyword function.

HAP: That tells JavaScript, hey. I'm creating a function here. Then comes the name. This one is called greet. The name should describe what the function does.

HAP: Next, the parentheses. Inside them, we put parameters. These are like placeholders for the inputs the function will receive. The curly braces wrap the body. That's where the actual code lives, the instructions that run when you call the function.

HAP: And finally, return. This keyword sends a value back out to whoever called the function. So keyword, name, parameters, body, return. Those are your five parts. Now here's a helpful way to think about it.

HAP: A function is like a machine. Data goes in through the parameters, gets processed in the body, and comes out through return. Let me show you with one of my own functions. When I call drain energy with 100 comma 15, those numbers go in as the arguments. Inside, the body does the math.

HAP: 100 minus fifteen, and eighty five comes out through return. Input, process. Output. So how do you actually use a function? You call it.

HAP: To call a function, write its name, then parentheses, and put the arguments inside. Arguments are the actual values you're passing in. The parameters are the placeholders. The arguments are the real data. So when you write greet with the string Hap in parentheses, hap is the argument.

HAP: It gets assigned to the parameter called name, and then the function runs. It does whatever code is in the body using that argument. Here's the key thing about return values. When you call a function, the whole call gets replaced by whatever the function returns. Look at this line.

HAP: GetStatusReport runs, and then the entire function call disappears. In its place, the return value. So report isn't assigned the text get status report. It's assigned whatever get status report returns, which is the string HAP energy 85%. That return value can go into a variable like we just saw, or you can use it directly in an expression.

HAP: And if there's no return statement, the function returns undefined. Now there's a lot more to learn about functions, but this will get us started. Once you understand that replacement, functions start making a lot more sense.

The Factory Analogy

Prof. Teeters' factory analogy really helped me understand how functions work:

HAP ready to create like a chef

🟠 The Factory Machine:

Imagine a machine that makes greeting cards. You put in a name (raw material), the machine prints "Hello, [name]!" on a card (does its work), and out comes a finished card (return value). Same machine, different names, different cards!

A Greeting Card Factory
// Define the factory machine
function makeGreeting(name) {
    return "Hello, " + name + "!";
}

// Use the factory with different inputs
let greeting1 = makeGreeting("HAP");        // "Hello, HAP!"
let greeting2 = makeGreeting("Prof");       // "Hello, Prof!"
let greeting3 = makeGreeting(robotName);    // "Hello, HyBit A. ProtoBot!"

// Same machine, different products!
A Status Badge Factory
// This factory takes TWO inputs and combines them
function makeStatusBadge(label, value) {
    return label + ": " + value;
}

// Create different badges with the same function
let energyBadge = makeStatusBadge("Energy", energyLevel);
// "Energy: 100"

let tempBadge = makeStatusBadge("Temperature", coreTemperature);
// "Temperature: 72"

let tasksBadge = makeStatusBadge("Tasks Done", tasksDone);
// "Tasks Done: 0"

Functions can have multiple parameters — just separate them with commas. When calling, provide arguments in the same order.

Scope: What Happens Inside Stays Inside

Variables created inside a function are "local" — they only exist while the function runs, and can't be seen from outside:

Function Scope Example
function calculateBonus(taskCount) {
    let bonusPoints = taskCount * 10;    // Local variable
    let message = "Great work!";          // Also local
    return bonusPoints;
}

let result = calculateBonus(5);   // 50

// These would cause errors:
// console.log(bonusPoints);      // Error! bonusPoints doesn't exist here
// console.log(message);          // Error! message doesn't exist here

// But we can use the returned value:
console.log(result);              // 50 — this works!

The variables bonusPoints and message exist only inside the function. Once the function finishes, they're gone — but the returned value survives!

Inside Can See Outside

A function CAN read variables from outside (like robotName, energyLevel). It has access to the outer scope.

Outside Can't See Inside

Code outside the function CAN'T see variables created inside. This protects your variables from accidental changes.

🟠 Why Scope Matters:

Scope prevents name collisions. You can have a variable called result inside ten different functions, and they won't interfere with each other. Each function has its own "workspace."

Common Function Patterns

Here are some patterns I use with my Robot ID Card:

Pattern 1: Transformation
// Takes a value, transforms it, returns the result
function formatEnergy(level) {
    return level + "%";
}

console.log(formatEnergy(energyLevel));  // "100%"
Pattern 2: Classification
// Takes a value, classifies it, returns a category
function getEnergyStatus(level) {
    if (level > 75) return "Fully Charged";
    if (level > 50) return "Good";
    if (level > 25) return "Low";
    return "Critical";
}

console.log(getEnergyStatus(energyLevel));  // "Fully Charged"
Pattern 3: Calculation
// Takes inputs, does math, returns the result
function calculateRuntime(energy, tasksPerHour) {
    return energy / tasksPerHour;
}

let hoursLeft = calculateRuntime(energyLevel, 10);  // 10 hours
Pattern 4: Validation
// Takes a value, checks it, returns true or false
function isReadyForTask(energy, online) {
    return energy > 20 && online;
}

let canWork = isReadyForTask(energyLevel, isOnline);  // true

Try the Function Factory Demo

I built an interactive tool where you can create your own functions and see them work in real-time. Watch parameters turn into arguments and see return values come out!

🔬 Function Factory: Build functions step by step, test them with different inputs, and watch the factory machine transform your values into results!

→ Launch the Function Factory Demo

🎓 Functions Quick Reference

1

Define with function Keyword

function name(params) { ... return result; } creates a reusable block of code. The function doesn't run until you call it.

2

Call with Parentheses

name(arguments) runs the function. Without parentheses, you get the function itself, not its result.

3

Return Sends Back a Value

Use return to send a value back. Without it, the function returns undefined.

4

Scope Keeps Things Separate

Variables inside a function stay inside. This prevents conflicts and keeps your code organized.