Using the for...of Loop for Array Iteration
Syntax
The for...of
loop is a more modern and concise way to iterate over arrays. It automatically handles the loop counter and provides direct access to each element's value. The syntax for a for...of
loop is as follows:
jsfor (const element of array) {// Code to be executed for each array element}
In this syntax:
const element
is a variable that stores the value of each element during each iteration;of array
specifies the array we want to iterate over.
Example
Here's an example of using the for...of
loop to achieve the same result as the previous for
loop:
const students = ["Brandon", "Mario", "Saul"]; for (const student of students) { console.log(student); }
- Line 1: It declares a constant variable named
students
and assigns it an array containing three strings -"Brandon"
,"Mario"
, and"Saul"
. This array represents a list of student names; - Line 3: It starts a
for...of
loop. The loop is used to iterate through each element in thestudents
array one at a time; - Line 4: Inside the
for...of
loop, we use theconsole.log()
function to log the value of the current element to the console. Thestudent
variable represents the current element in the array during each loop iteration. So, in the first iteration, it will be"Brandon"
, in the second iteration,"Mario"
, and in the third iteration,"Saul"
.
1. What is the primary advantage of using a for...of
loop when iterating over arrays?
2. In the for...of
loop syntax, what does the const element
represent?
3. What is the purpose of the of array
part in the for...of
loop syntax?
Takk for tilbakemeldingene dine!