// Declare an array
var myArray = [”John”, “Callum”, “Paul”, “Frank”];
// If i is less than the value of the size of the array (4), then run the code
for(var i = 0; i < myArray.length; i++) {
// Log to the console the array with the index position that’s the same as the value of i
console.log(”Hello my name is “ + myArray[i]);
}
Hopefully the comments give an insight into what is happening here, but let’s talk through it anyway. We first declare an array, just like we have done many times in the past. Then the loop we have written will run for a total of four times, which we defined with our condition statement i < myArray.length.
This statement is the same as writing i < 4, however, because we have set the condition equal to the size of the array. If you ever want to add data to the array, you won’t need to rewrite this loop, as the loop’s condition statement has been dynamically set.
Each time the loop runs we output the statement ‘Hello my name is [name]’, [name] being replaced by the value of the element in that position in the array. Therefore, after this loop has run, the console would look like this:
Yet we only wrote the code once. How powerful is that? We were able to dynamically create a bunch of statements from a small snippet of code. This is the principle of programming. We are writing small chunks of code to carry out complex operations for us that we would otherwise have to do manually. Seriously, how great is programming?
When writing for loops it is important to consider that all three statements are optional; you can omit any one of them and the loop will still run. Just make sure that you write a condition for the loop to break or the loop will run endlessly and crash the system, so realistically you wouldn’t ever want to leave out the second condition statement.
This loop is used for looping through the properties of an object. Similar to the standard for loop, it is used to iterate through and perform an action on each individual property of an object. Its syntax is nice and succinct. It’s an easy loop to use and understand, so let’s breeze through it nice and quickly.