JavaScript For In Loop
The for...in
loop is a type of loop in JavaScript that allows you to iterate over the properties of an object.
The basic syntax of a for...in
loop is as follows:
for (variable in object) {
// code to be executed
}
Explanation:
variable
: This is a variable that will be assigned the name of each property in the object.object
: This is an object whose properties you want to iterate over.
Here's an example of a for...in
loop that prints the properties of an object to the page:
Editor
Loading...
In this example:
- HTML code creates an unordered list (
<ul>
) with an ID of personList. - Then uses a
for...in
loop to iterate over the properties of theperson
object. For each property, it creates a list item (<li>
) and sets its text content using a template literal that combines the property name and its value. - Finally, the list item is added to the
ul
element usingappendChild
.
For ...of
Over Arrays
It is recommended to use the for...of
loop to iterate over arrays in JavaScript.
The for...of
loop is designed specifically for iterable objects like arrays, and it avoids iterating over any properties that may be added to the object's prototype chain.
Example:
const numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
console.log(number); // 1,2,3,4,5
}
In this example:
- The
for...of
loop iterates over the elements of thenumbers
array. - For each iteration, the value of the current element is assigned to the
number
variable. - The
console.log()
method prints the value of thenumber
variable to the console.