Loops




For Loop

  • for (initialExpression;condition;incrementExpression;) {
    • "do something until condition is met"
    }
  • const forLoop = () => {
    • const MAX_LENGTH = 10;
    • // Runs 10 times,
    • for ( let index = 0;index < MAX_LENGTH;index++;) {
      • // start values = 0; end value = MAX_LENGTH - 1 = 9; increment by 1;
      • console.log(index)
      }
    }
  • // Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9



For In

Loop through all the properties of an object.

Avoid using "For in" in arrays, you might get unexpected results. Use "For of" instead.

  • Will include "Array.prototype" in the result
  • Will ignore undefinted indexes in the array
  • for (variableinobject) {
    • for each propertie in object, do something
    }
  • const home = {model:"A36", rooms:"6", price:"2Mil", location:"Holliwood"};
  • let properties = "";
  • for (let propertyIndexinperson) {
    • properties += home[propertyIndex] + " ";
    }
  • console.log(properties)
  • // Output: "A36 6 2Mil Holliwood"



While Loop

To prevent an infinite loop, make sure that the condition eventualy becomes false

  • Declear and set variable used in the wile loop condition
  • while (condition) {
    • "do something until condition is met"
    • increment variable to move towards condition
    }
  • let i = 0;
  • while (i < 10) {
    • console.log(i);
    • i++;
    }
  • // Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9



Do While Loop

Statement is always executed once before the condition is checked

  • Declear and set variable used in the wile loop condition
  • do {
    • increment variable to move towards condition
    • "do something until condition is met"
    } while (condition);
  • let i = 0;
  • do {
    • i += 1;
    • console.log(i);
    } while (i < 5);