JavaScript for of loop
The JavaScript for...of
loop is a control structure that allows you to iterate over elements of an iterable object, such as arrays, strings, maps, sets, etc. The for...of
loop was introduced in the JavaScript ES6. The for...of
loop consists of two parts: the for
keyword and the of
keyword.
Here's the basic syntax of the JavaScript for...of
loop:
1for (let element of iterable) { 2 // code to be executed 3}
In this example, the element
variable is used to store the value of the current element being processed in each iteration of the loop. The iterable
is the object whose elements you want to iterate over.
Here's an example of how to use the for...of
loop to print the elements of an array:
1const numbers = [1, 2, 3, 4, 5]; 2 3for (let number of numbers) { 4 console.log(number); 5} 6 7// Output: 8// 1 9// 2 10// 3 11// 4 12// 5
In this example, the numbers
array has five elements: 1
, 2
, 3
, 4
, and 5
. The for...of
loop is used to iterate over the elements of the numbers
array. The number
variable is used to store the value of the current element being processed in each iteration of the loop.
The JavaScript for...of
loop is useful when you need to iterate over elements of an iterable object and perform actions, such as printing values, counting elements, or updating values. Unlike the for...in
loop, the for...of
loop does not include properties from the prototype chain, so you don't need to use the hasOwnProperty()
method to exclude properties from the prototype.