Using Loops in JavaScript

Using For Loops in JavaScript

Some of the most powerful and intriguing JavaScript tools I learned about are loops. When a code block needs to be executed multiple times using different data, a For Loop can be used to reiterate the code block using a variable that changes during each iteration. For example, you can use the code listed below to log the numbers 0 through 4.

To set up a loop, we need to establish the Condition which is made up of three pieces of information, separated by semicolons, within parentheses. First, we declare the variable and set it to whatever value we would like to start at (usually 0). Next, we will determine how many iterations we would like the code to run. If I want the code to stop running once X reaches 5, I can set it to only run while X is less than 5. Finally, we declare how we would like the variable to change between iterations. In this example I have coded the variable to increase by one during each iteration, but depending upon the application of the program, you could set it to increase by 2, decrease by 1, multiply by 3, or any other mathematical operation.

When this loop is executed, the value of X begins at 0. The code block is executed and the value of X is logged. Then the value of X is increased by one in accordance to the final piece of information that we added to the condition, making the X equal 1. The code block will continue to repeat with the new value of X until it is no longer less than 5, leaving us with console logs of 0, 1, 2, 3, and 4.


for(var x = 0; x < 5; x++){
	console.log(x);
}


This technique can be especially powerful when used in conjunction with an Array. Take for instance the array and loop examples below. The code block will execute similarly to the previous example, but instead of logging the current element (the value of X during the iteration of the loop), the JavaScript code will find the object within the array whose index is equal to X and console log its title value. This will repeat until x is no longer less than the length of the Array, which is always one more than the index of the last entry.

Array

var albums = [
	{title: “A Hard Day’s Night”, year: “1964”},
	{title: “Help!”, year: “1965”},
	{title: “Sgt. Pepper's Lonely Hearts Club Band”, year: “1967”},
	{title: “Abbey Road”, year: “1969”},
	{title: “Let It Be”, year: “1970”},
]

Loop

for(var x = 0; x < albums.length; x++){
	console.log(albums[x].title);
}