Javascript basics in for

for loop

  • This is used for when working with arrays.

  • Loops through a block of code number of times.

 const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];

        let text = "";
        for (let i = 0; i < cars.length; i++) {
        text += cars[i] + ",";

        }
console.log(text);

output:BMW, Volvo, Saab, Ford, Fiat, Audi

for in

  • It loops through the properties of an object.

  • It iterates automatically based on a key and then the key is used to get that access value.

  • We can use this for array also but when index matters use array.foreach()

  • foreach() takes three arguments item value,item index, array itself

       const person = {fname:"John", lname:"Doe", age:25};
    
      let text = "";
      for (let x in person) {
        text += person[x] + " ,";
      } 
      console.log(text);
    
      Output: John , Doe , 25
    

for of

  • It loops through the value of an iterable object.

  • It loops over through the iterable datastructures like arrays,Strings,maps,nodelists and more.

       const cars = ["BMW", "Volvo", "Mini"];
    
              let text = "";
              for (let x of cars) {
              text += x + ",";
              }
              console.log(text);
    
      output: BMW,Volvo,Mini,