for(let i=0;i< 5;i++){
console.log(i);
}
// Output: 0, 1, 2, 3, 4
Iterates over properties of an object. You have to know how to decalare of an object
const obj={a:1,b:2,c:3};
for(let x in obj){
console.log(x, obj[x]);
}
// Output: a 1, b 2, c 3
works with iterable object like array, string.
const arr=[1,2,3];
for(let x of arr){
console.log(x);
}
// Output: 1, 2, 3
Loops help generate HTML content dynamically, like creating table rows or list items based on data fetched from an API.
const users = ['Alice', 'Bob', 'Charlie'];
let userList = '';
for (let user of users) {
userList += `<li>${user}</li>`;
}
document.getElementById('user-list').innerHTML = userList;
const fields = document.querySelectorAll('input');
for (let field of fields) {
if (!field.value) {
alert(`${field.name} is required`);
}
}
After fetching data from an API, loops are used to proccess and display this data
fetch('https://api.example.com/users')
.then(response => response.json())
.then(users => {
for (let user of users) {
console.log(user.name);
}
});