I'm new to JavaScript and understand the basic ideas behind functions and loops separately, but I get stuck when I have to write code that uses them together. I'm often unsure how to begin or what steps to take. Are there particular learning materials or exercises that explain this clearly, or is regular practice the main way these concepts start to feel natural?
3 Answers
Don’t feel discouraged if it doesn’t click immediately. Break the code into small pieces, trace one loop iteration at a time, and practice changing or rewriting short examples. Repetition and experimenting will help the relationship between the loop and the function become familiar.
Practice is a big part of it. Read small examples that combine loops and functions, run them, change the values, and then try writing a similar example from scratch. After using the pattern several times, it usually becomes much easier to recognize.
Try predicting what simple code will do before running it. For example, this function prints the square of a number, and the loop calls it for every value from 1 through 5:
function printSquare(i) {
console.log(i * i);
}
for (var x = 1; x <= 5; ++x) {
printSquare(x);
}
The output is 1, 4, 9, 16, and 25. The loop supplies each number to the function, while the function handles the calculation and printing.

That makes sense—the loop goes through the numbers, and each number gets passed into the function. I predicted the output correctly.