Using a loop inside a function
A function that loops up to its parameter n, adds each number to a total declared inside it, then returns that total after the loop ends so the caller gets the finished answer.
Understanding Using a loop inside a function in ACARA Digital Technologies Years 7–8
What it does: The return statement sits outside the closing brace of the loop, so all the repeats finish before the total is sent back. The condition i <= n makes the loop stop at the number passed into the function, so sumTo(5) repeats 5 times. With i < n the loop stops before n, so sumTo(4) would give 6 instead of 10. Using <= includes n. total is declared inside the function, so code outside can't see it. The caller gets the answer from the returned value of sumTo(5). total += i adds i to the running total. total = i replaces the total each pass, so only the last number is kept.
Common mistakes: The loop uses i < n, so it stops before adding n. sumTo(5) would give 10 instead of 15. It should be i<=n so the last number is included. The function has no parameter, so n is not defined inside the loop condition. The header should be function countEvens(n) {.
Free printable worksheet with full answer key — or add this module to a class and your students practise it interactively.
This module's key terms are also in a printable crossword (Modules 611–623) and word search (Modules 611–634).
Take this worksheet further — free with Cloodit
Each concept is reinforced from every angle — learned, then applied, then tested.
Cloodit turns curriculum-aligned coding content into journeys students work through one biome at a time.
Over 100 of them, across seven natural biomes.
Turns their work into revision material ready for Flash Cards and Exam study.
Live, competitive practice for the start of the lesson or a teacher-led lesson finisher.
Honour your top performers, or encourage a student who's trying hard — ready to print in seconds.
Quick Questions
let total = 0; be declared in sumTo(n)?return total; as the very first line inside the for loop body. What happens?Match the Pairs
Key Term
function sumTo(n)Fill in the Blanks
Spot the Error
Student with a class code? Join your class →