Using Loops with Arrays
Loops enable us to efficiently go through all or specific elements of an array.
For example, we can use a for loop to iterate through all elements of an array and output them:
12345let numbers = [1, 1, 2, 3, 5, 8, 13, 21]; for(let i = 0; i < numbers.length; i++) { console.log("Element " + (i + 1) + " of the array is: " + numbers[i]); }
This is especially useful when we need to perform an operation on multiple elements in an array:
1234567let numbers = [1, 1, 2, 3, 5, 8, 13, 21]; console.log("Before:", numbers); for(let i = 0; i < numbers.length; i++) { numbers[i] *= 2; } console.log("After:", numbers);
We can use a while or a do-while loop for this purpose as well, however, that is not the convention.
123456789let numbers = [1, 1, 2, 3, 5, 8, 13, 21]; console.log("Before:", numbers); let i = 0; while(i < numbers.length) { numbers[i] *= 2; i += 1; } console.log("After:", numbers);
Even though the same results can be achieved using while or do-while loops, it is recommended to use a for loop when iterating through arrays because it is the conventional and more readable approach.
1. What does the following code output?
2. Does the following code modify the original array?
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain why a for loop is preferred over a while loop for array iteration?
How can I use these concepts to update specific elements in an array?
Can you show an example of iterating through two arrays at the same time?
Awesome!
Completion rate improved to 1.33
Using Loops with Arrays
Swipe to show menu
Loops enable us to efficiently go through all or specific elements of an array.
For example, we can use a for loop to iterate through all elements of an array and output them:
12345let numbers = [1, 1, 2, 3, 5, 8, 13, 21]; for(let i = 0; i < numbers.length; i++) { console.log("Element " + (i + 1) + " of the array is: " + numbers[i]); }
This is especially useful when we need to perform an operation on multiple elements in an array:
1234567let numbers = [1, 1, 2, 3, 5, 8, 13, 21]; console.log("Before:", numbers); for(let i = 0; i < numbers.length; i++) { numbers[i] *= 2; } console.log("After:", numbers);
We can use a while or a do-while loop for this purpose as well, however, that is not the convention.
123456789let numbers = [1, 1, 2, 3, 5, 8, 13, 21]; console.log("Before:", numbers); let i = 0; while(i < numbers.length) { numbers[i] *= 2; i += 1; } console.log("After:", numbers);
Even though the same results can be achieved using while or do-while loops, it is recommended to use a for loop when iterating through arrays because it is the conventional and more readable approach.
1. What does the following code output?
2. Does the following code modify the original array?
Thanks for your feedback!