Conteúdo do Curso
JavaScript Data Structures
JavaScript Data Structures
for...of Loop
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:
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"
.
Obrigado pelo seu feedback!