Let’s say you want to run a function, bounceBall, four times. Would you do it like this?
function bounceBall() { // bounce the ball here}
bounceBall()bounceBall()bounceBall()bounceBall()This approach is great if you need to bounceBall only for a few times. What happens if you need to bounceBall for a hundred times? Like this?
function bounceBall() { // bounce the ball here}
bounceBall()bounceBall()bounceBall()bounceBall()bounceBall()//... 95 more lines of bounceBall()The better way is through a for loop.
for loop
A for loop runs a block of code as many times as you want to. Here’s a for loop that runs bounceBall ten times:
for (let i = 0; i < 10; i++) { bounceBall()}It’s broken down into four parts – the initialExpression, the condition, the incrementalExpression and the statement:
for (initialExpression; condition; incrementExpression) { statement}Before you loop, you need to have a statement. This statement is the block of code you’d like to run multiple times. You can write any number of lines of code here. You can even use functions.
Here’s what the for loop looks like with bounceBall as its statement:
for (initialExpression; condition; incrementExpression) { bounceBall()}Next, you need an initial expression to begin a loop. This is where you declare a variable. For most loops, this variable is called i. It’s also set to 0.
Here’s how it’ll look like when you put the initialExpression into the for loop:
for (let i = 0; condition; incrementExpression) { bounceBall()}After the statement runs, the variable, i is increased or decreased. You increase or decrease the value of i in the increment expression.
To increase the value of i by one, you reassign i such that it becomes i + 1 with i = i + 1. The shorthand for this reassignment is i++, which is what you’ll find in most for loops.
To decrease the value of i by one, you reassign i such that it becomes i - 1 with i = i - 1. The shorthand for this reassignment is i--, which is another variation of what you’ll find in most for loops.
In the bounceBall example above, we increased the variable i by one each time the code runs:
for (let i = 0; condition; i++) { bounceBall()}But should you increase or decrease i?
The answer lies in the condition. This condition evaluates either to true or false. If the condition evaluates to true, the statement runs.
After the statement ran, JavaScript runs the increment expression and checks if the condition evaluates to true again. It repeats this process until the condition evaluates to false.
Once the condition evaluates to false, JavaScript skips the loop and moves on with the rest of your code.
So, if you do not want the loop to run, you can set a condition that evaluates to false immediately:
// This loop will not run since the condition evaluates to falsefor (let i = 0; i < 0; i++) { bounceBall() const timesBounced = i + 1 console.log('The ball has bounced ' + timesBounced + ' times')}
// You will only see thisconsole.log('next line of code')
If you want the loop to run twice, you change the condition such that it evaluates to false when the increment expression has run twice.
// This loop will run twicefor (let i = 0; i < 2; i++) { bounceBall() const timesBounced = i + 1 console.log('The ball has bounced ' + timesBounced + ' times')}
console.log('next line of code')
If you want the loop to run ten times, you change the condition such that it evaluates to false when the increment expression has run ten times.
// This loop will run ten timesfor (let i = 0; i < 10; i++) { bounceBall() const timesBounced = i + 1 console.log('The ball has bounced ' + timesBounced + ' times')}
console.log('next line of code')
Let’s run through the for loop together
Many beginners get confused with a for loop, so let’s slow down and run through the for loop together.
For this section, we’re going to use this code:
for (let i = 0; i < 2; i++) { const timesBounced = i + 1 console.log('The ball has bounced ' + timesBounced + ' times')}
console.log('next line of code')When JavaScript sees the for loop for the first time, declares a variable i and sets it to 0. After declaring the variable, it checks if the condition is true.
In this case, i is 0; the condition is true; JavaScript executes the block of code within the for loop.
Next, JavaScript executes the block of code; it replaces i with 0 whenever it sees i.
Since i is 0, timesBounced is 0 + 1 = 1.
After running through the block, JavaScript runs the incrementExpression. Here, JavaScript recognizes that the current value of i is 0, and it needs to add one to i. The new value of i becomes one.
Next, JavaScript runs the condition again. This time, it replaces i with one because the new value of i is one.
Since 1 < 2 evaluates to true, JavaScript runs the block of code within the for loop once more. This time, it sets i as 1. Because i is 1, timesBounced will be 2.
Next, JavaScript runs the incrementExpression and increases i to 2.
Then, JavaScript runs the condition again. This time, i is 2.
Since 2 < 2 evaluates to false, JavaScript skips the for loop and executes the next line, which logs “next line of code”.
Logic within for loops
You can use if/else or any other conditions within a for loop.
const numbers = [25, 22, 12, 56, 8, 18, 34]
for (let i = 0; i < numbers.length; i++) { const num = numbers[i] if (num < 20) { console.log(num + ' is less than 20!') }}Infinite loops
Infinite loops occur when the condition for a loop always return true. Your browser will hang if you run an infinite loop.
Here’s an example of an infinite loop.
for (let i = 0; i < 1; i--) { console.log('HAHA! You are stuck!')}To recover from an infinite loop, you need to quit your browser forcefully. On a Mac, this means you right click on your browser icon and select “force quit”. On a Window’s machine, you open the Windows Task manager with ctrl + alt + del, select your browser, and click “End task”.
Looping through arrays
In practice, you almost never write a loop that runs ten times like in the bounceBall example above. You’d always loop through an array or a object.
When you loop (or iterate) through an array, you go through each item in the array once. To do so, you can use the length of the array as a condition:
const fruitBasket = ['banana', 'pear', 'guava']
// fruitBasket.length is 3for (let i = 0; i < fruitBasket.length; i++) { console.log("There's a " + fruitBasket[i] + ' in the basket')}
// => There's a banana in the basket// => There's a pear in the basket// => There's a guava in the basketYou can also write a for loop with a negative incrementExpression. It runs faster than the positive incrementExpression version, but loops from the last item. Use this if you need to run a super performant app. (Usually, you don’t have to worry about loop performance).
for (let i = fruitBasket.length - 1; i >= 0; i--) { console.log("There's a " + fruitBasket[i] + ' in the basket')}
// => There's a guava in the basket// => There's a pear in the basket// => There's a banana in the basketThe “for of” loop
A (much better) way to loop through an array to use a for...of loop. This is a new loop syntax that comes with ES6. It looks like this:
const fruitBasket = ['banana', 'pear', 'guava']for (let fruit of fruitBasket) { console.log("There's a " + fruit + ' in the basket')}
// => There's a banana in the basket// => There's a pear in the basket// => There's a guava in the basketThe for...of loop is preferable to the standard for loop because it always loops through the array once. It makes your code easier to read and maintain because you don’t have to worry about the increment expression nor the number of loops (with array.length).
You can use for...of with any iterable object. These are objects that contain the Symbol.iterator property. Arrays are one of such objects. If you console.log an empty array, you’ll see that it has the Symbol.iterator as one of its keys (within the Array __proto__ key):
Exercise
Practice using the for and for of to loop through an array of numbers (given below). Do the following tasks:
- Loop through the numbers and
console.logeach number within - Loop through the numbers. If the numbers are greater than 5,
console.logthem - Create a new array. Add all numbers that are greater than 10 into this new array. (Hint: You have to loop through the
numbersarray first) - Create a new array. Multiply all numbers by 5 and put them into the new array. (Hint: You have to loop through the
numbersarray first)
Here’s the array of numbers to use for this exercise:
const numbers = [1, 12, 4, 18, 9, 7, 11, 3, 50, 5, 6]Here’s the array of numbers to use for this exercise:
const numbers = [1, 12, 4, 18, 9, 7, 11, 3, 50, 5, 6]Loop through the numbers and console.log each number within
for (const num of numbers) { console.log(num)}Loop through the numbers. If the numbers are greater than 5, console.log them.
for (const num of numbers) { if (num > 5) console.log(num)}Create a new array. Add all numbers that are greater than 10 into this new array.
let array = []for (const num of numbers) { if (num > 10) { array.push(num) }}Create a new array. Multiply all numbers by 5 and put them into the new array. (Hint: You have to loop through the numbers array first).
let array = []for (const num of numbers) { array.push(num * 5)}Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson