100+ JavaScript

Loop In JS Function localStorage Drag Drop Object get set

Asynchronous JS

Callback Promises

Web API

Web API Intro Cookie Fetch API

JS PDF

Basic Pdf

Toast.js

Basic Toastr

➰Learn about all types of loops in JS➿

A JavaScript loops allows you to repeatedly execute a block of code untill a specified condition is met.

JS supports different kinds of loops
  • for loop runs a block of code multiple times.
  • for/in loop through the properties fo an object
  • for/of loops through the value of iterable object(array, string, maps, set etc)
  • while loops repeats as long as condition is true.
  • do..while loop execute the block of code at least once, then contious if the condition is true.

for


for(let i=0;i< 5;i++){
    console.log(i);
}
// Output: 0, 1, 2, 3, 4

for/in

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

for/of

works with iterable object like array, string.


const arr=[1,2,3];
for(let x of arr){
    console.log(x);
}
// Output: 1, 2, 3

🌐Application🈸

Dynamic Content Generation

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;
    
    

Form Validation

    
    const fields = document.querySelectorAll('input');
    for (let field of fields) {
        if (!field.value) {
            alert(`${field.name} is required`);
        }
    }   
    
    

API Data Handling

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);
        }
    });