For of vs For in JavaScript Loops
JavaScript, Web Design
In JavaScript there are two kinds of for loops: for of and for in. The difference can be seen when looping through arrays. Let’s take this array for example:
var greetings = [“Hi”,”Hey”,”Hello”]
It’s just a normal array with three strings (words) in it called greetings. If I were to apply the for in loop to it like this:
for(x in greetings){
document.write(x + “<br>”);
}
This would print out the index positions of each value in the array. So we’d get 0, 1, and 2 printed out to the page on their own lines. If we wanted to pull the values of each index position we could do it this way:
for(x in greetings){
document.write(greetings[x] + “<br>”);
}
Here we are using square bracket notation to use the index position to pull the values of the array. The first time the loop runs it will pull greetings[0] which would give us “Hi” then it would be greetings[1] which would give us “Hey” but there’s an easier way to pull the values of an array. We can do it with the for of loop like so:
for(x of greetings){
document.write(x + “<br>”);
}
This would print out the three values, “Hi”, “Hey” and “Hello” to the page. Instead of returning the index positions of the array like the for in loop did, the for of loop returns the values of the array so we don’t need to worry about the square brackets notation. Nifty eh? If you’d like to learn more be sure to check out our JavaScript training. Have an amazing day!