skip to content
Dev Journal

Mastering the Art of Loops: Running Code Efficiently

/ 2 min read

Let’s say you want to bounce a ball a few times. You might start by calling a function, bounceBall(), like this:

function bounceBall () {
// bounce the ball here
}
bounceBall()
bounceBall()
bounceBall()
bounceBall()

This is fine for a few bounces, but what if you need a hundred? Writing bounceBall() a hundred times is impractical. Enter the for loop!

Introducing the for Loop

A for loop lets you run a block of code multiple times. Here’s how you can bounce the ball ten times:

for (let i = 0; i < 10; i++) {
bounceBall()
}

The structure of a for loop is straightforward:

for (initialExpression; condition; incrementalExpression) {
statement
}
  • initialExpression: Initialize the loop variable, usually let i = 0.
  • condition: Keeps the loop running as long as it’s true.
  • incrementExpression: Updates the loop variable, typically i++.

Breaking Down the Loop

Let’s dive into the loop’s components:

  1. Initialization: let i = 0 sets the starting point.
  2. Condition Check: i < 10 keeps the loop going.
  3. Execute Statement: Runs the code inside { }
  4. Increment: i++ increments i by one.

Here’s a practical example:

for (let i = 0; i < 2; i++) {
const timesBounced = i + 1;
console.log("The ball has bounced " + timesBounced + " times") // 2 times
}

This loop runs twice, logging how many times the ball has bounced.

Beware of Infinite Loops

An infinite loop happens when the condition never becomes false. For example:

for (let i = 0; i < 1; i--) {
console.log("Stuck in an infinite loop!");
}

This will hang your program. You may need to force quit your browser to stop it.

Looping Through Arrays

Often, you’ll loop through arrays:

const fruitBasket = ["banana", "pear", "guava"]
for (let i = 0; i < fruitBasket.length; i++) {
console.log("There's a " + fruitBasket[i] + " in the basket")
}

The for...of Loop

A cleaner way to loop through arrays is with the for...of loop:

const fruitBasket = ['banana', 'pear', 'guava']
for (let fruit of fruitBasket) {
console.log('There\'s a ' + fruit + ' in the basket')
}

This loop is simpler and avoids manual indexing.

Wrapping Up

  • Use a for loop to run code multiple times efficiently.
  • for...of loops provide cleaner syntax for arrays.
  • Avoid infinite loops by ensuring the condition can eventually become false.

Mastering loops will help you write more efficient and maintainable code. Happy coding!