Functions, Arrays and Debugging
Organize code into reusable functions, store collections in arrays and objects, meet stacks and queues, and practice a systematic way to find and fix bugs.
Welcome back!
Step 1 of 15Learn
Functions: reusable building blocks
Imagine a game that calculates a player's damage in 40 different places. If the formula changes, you'd have to find and fix all 40 copies, and you'd probably miss one. Functions solve this.
A function is a named, reusable block of code. It takes inputs, called parameters, does some work and can return a result:
function area(width, height) {
return width * height;
}
let room = area(4, 5); // room is 20When you call area(4, 5), the values 4 and 5 (the arguments) are placed into the parameters width and height, the body runs, and return sends the result back to where the call was made. Code after a return in the same function doesn't run.
Functions give you:
- Reuse: write once, call anywhere.
- Abstraction: callers only need to know what
areadoes, not how. - Testing: you can check a function on its own with known inputs and expected outputs, exactly as the code exercises in this course do.
- Readability:
calculateShipping(cart)explains itself.
A good function does one job and has a name that says what that job is. If you struggle to name a function, it's probably doing too much.
Variables created inside a function are local: they exist only while the function runs and can't be seen from outside. This keeps functions from accidentally interfering with each other.
Step 2 of 15Practice · Fill in the blanks
Fill in the blanks
In function greet(name) { return "Hi " + name; }, name is called a . In the call greet("Sam"), the value "Sam" is called an . The keyword that sends a result back to the caller is .
Step 3 of 15Diagram
What happens in greet("Sam")
Tap a shape with to see more.
- Call with argument "Sam"
- Parameter name = "Sam"
The parameter is a local variable that receives the argument.
- Body runs
Builds "Hi " + name.
- return "Hi Sam"
The value goes back to where the function was called.
Step 4 of 15Practice · Code challenge
Write celsiusToFahrenheit(c) that converts a temperature using F = C × 9/5 + 32.
celsiusToFahrenheit(0)celsiusToFahrenheit(100)celsiusToFahrenheit(-40)celsiusToFahrenheit(37)
Step 5 of 15Learn
Arrays: ordered collections
Most programs work with collections: a playlist of songs, a list of test scores, the pixels of an image. An array stores an ordered list of values under one name:
let scores = [72, 88, 95, 61];
scores[0] // 72 (the first item)
scores[3] // 61 (the fourth item)
scores.length // 4
scores.push(80); // adds 80 at the end; length is now 5The crucial detail: in JavaScript and most languages, indexes start at 0. The first item is scores[0] and the last is scores[scores.length - 1]. Asking for scores[4] in a 4-item array gives undefined, because no fifth item exists. This zero-based indexing causes countless off-by-one bugs.
The standard way to process every item is a loop:
let best = scores[0];
for (let i = 1; i < scores.length; i++) {
if (scores[i] > best) best = scores[i];
}That's the "find the largest" algorithm from the first lesson, now in real code. Reading an item by its index is O(1), and a loop over all items is O(n).
For data with named parts, JavaScript has objects: { name: "Ada", grade: 95 }. You read a part with a dot, like student.grade. Arrays of objects, like a list of students, are among the most common structures in real programs.
Step 6 of 15Practice · Diagram
scores = [72, 88, 95, 61]: index → value
Which box does scores[scores.length - 1] read? Tap it.
Tap the shape that answers the question, then press Check.
- [0] → 72
The first item is at index 0.
- [1] → 88
- [2] → 95
- [3] → 61
The last index is length − 1, here 4 − 1 = 3.
Step 7 of 15Practice · Work it out
Given let colors = ["red", "green", "blue", "yellow", "purple"];, what index does "purple" have?
Step 8 of 15Practice · Code challenge
Write average(nums) that returns the average of an array of numbers. If the array is empty, return 0.
average([2, 4, 6])average([10])average([])average([1, 2])
Step 9 of 15Learn
Stacks and queues
Arrays can be used to build two simple but important data structures, defined by the order in which items come out.
A stack is last in, first out (LIFO), like a stack of plates: you add to the top and take from the top. Your browser's Back button uses a stack: each page you visit is pushed on top, and Back pops the most recent one. "Undo" in an editor works the same way. In JavaScript, push adds to the end of an array and pop removes from the end.
A queue is first in, first out (FIFO), like a line at a coffee shop: the first person to arrive is served first. Print jobs, messages waiting to be processed and the OS's list of tasks waiting for the CPU are queues. In JavaScript, push adds to the end and shift removes from the front.
Choosing the right data structure is part of designing an algorithm. Stacks naturally handle anything nested or reversible: matching brackets, undo history, exploring a maze and backtracking. Queues handle anything that must be processed fairly in arrival order.
Other structures you'll meet later include hash tables (fast lookup by key, like a dictionary), trees (hierarchies such as folders) and graphs (networks such as roads or social connections).
Step 10 of 15Practice · Sort into groups
Which structure best models each situation?
Tap an item, then tap its group (or drag it there).
Step 11 of 15Compare
Stack vs queue
| Aspect | Stack (LIFO) | Queue (FIFO) |
|---|---|---|
| Comes out first | The newest item | The oldest item |
| Everyday picture | A pile of plates | A line at a ticket counter |
| In JavaScript | push() to add, pop() to remove | push() to add, shift() to remove |
| Software uses | Undo, Back button, function calls | Print jobs, message processing, breadth-first search |
Step 12 of 15Note
Step 13 of 15Note
Step 14 of 15Practice · Spot the mistake
This function should return the last item of an array, but it returns undefined. Tap the line with the bug.
Step 15 of 15Practice · Choose one
After running let s = []; s.push(1); s.push(2); s.push(3); s.pop(); s.push(4);, what does s contain?
Lesson complete!