For-in Loop

Other Loops

For-in Loop

🙋 Need help? Ask an expert now!

The for-in loop iterates over the properties of an object. If the object is an array, the loop will iterate over the elements. The for-in loop is an advanced loop used when dealing with objects, a concept you will learn more about as you continue the course. For now, take a look at the sample code below to see if you understand what is happening.

Although the concept of arrays have not been covered in the course, you might be able to deduce what the for-in loop is doing in the code above. The array basically stores the numbers 1 through 6 as an element of the array. The variable index is a local variable that is created with the for-in loop and is used to access the elements of the array. Be sure to revisit this loop after learning about arrays and objects and see if you can utilize this loop in the future.

Edit Me on GitHub!

Application Question

Consider the following code segment:

var arr = [1, 1, 2, 3, 5, 8, 13, 21];
var sum = 0;
for (var index in arr) {
    sum += arr[index];
}
console.log(sum);

What number is printed to the console after the for-in loop is executed?