Lessons · JavaScript · counting loops
Counting with a loop
for (let i = 0; i < n; i++) counts from 0 up to but not including n.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Repeating something n times, indexing arrays, building sequences.
How to think about it
How many turns do I want, exactly? Three parts: start, keep-going condition, step. Start at 0 and use < n and you get exactly n turns. Use Array.from({length: n}, (_, i) => i) when you want the numbers as a list.
Worked example
for (let i = 0; i < 3; i++) console.log(i);0 1 2. Three turns.
Array.from({ length: 4 }, (_, i) => i * 10)[0, 10, 20, 30].Your turn
Count from 1 to 5 inclusive.
for (let i = 1; i 5; i++) console.log(i);
Solve one with the tests running
The trap
<= n where you meant < n: one extra turn, usually reading past the end of an array.
Practise counting loops on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.