JAVASCRIPT / CHAPTER 05
Functions and loop boundaries
BeginnerBuild small functions with explicit return contracts.
By the end of this chapter
- Separate returned results from printed output
- Trace early returns
- Choose inclusive and exclusive loop bounds
The idea
A function names a transformation from arguments to a result. Its parameters are local bindings, and return sends a value to the caller while ending that invocation. Printing is a separate side effect: console.log helps inspection but does not replace a return value. State accepted inputs and the required output before writing the body.
Loops repeat a controlled step. For an array, indices begin at zero and the last valid index is length minus one, so a less-than comparison is usually the correct upper bound. An accumulator records progress between iterations. Decide its starting value using the empty-input case, then verify that every iteration preserves the meaning you assigned to it.
function totalPositive(values) {
let total = 0;
for (const value of values) {
if (value > 0) total += value;
}
return total;
}
console.log(totalPositive([3, -2, 4]));7
The accumulator begins at zero and includes only positive values. The function also returns zero for an empty array.
Try it yourself
Return the first index containing a negative number, or -1 if no negative value exists.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
Open JavaScript coding challengesCHECK YOUR UNDERSTANDING