For Loops

How For Loops Work

Loops let you repeat a block of code multiple times and for loop is one of the most commonly used types of loop in JavaScript. They follow three key parts; the initialising expression, condition, and incrementing expression separated by semi colons within parentheses after the keyword for.

for (initialisingExpression; condition; incrementingExpression) {
// code to repeat
}
  • initialisingExpression: runs once at the beginning (e.g., let i = 0)
  • condition: evaluated before each loop; if true, the loop runs
  • code block: runs if the condition is true
  • incrementingExpression: runs after the code block each time
  • Repeats until the condition is false
  • Then the program moves on to any code outside the loop
  • The initialising expression creates a temporary variable that acts as a counter for the loop. The condition keeps the loop working until it is met and the incrementing expression tells the loop how to increase the initialising expression each time. For example this would log the numbers from 1 to 10 (remember ++ means +1 each time).
  • for (let i = 1; i <= 10; i++) {
        console.log(i);
    }
    

    For In

    for...in is used to iterate over an object's keys (property names). It follows the syntax of defining a temporary variable to the keys in the object to iterate through (you may just see it defined as let key), then if statements checking if the object has the key including the code to execute.

    for (let temporaryVariable in objectName) {
        if (objectName.hasOwnProperty(temporaryVariable)) {
            // Code to execute
        }
    }
    
    const person = {
      name: "Adam",
      age: 34,
      job: "Engineer"
    };
    
    for (let temporaryVariable in person) {
      if (person.hasOwnProperty(temporaryVariable)) {
        console.log(temporaryVariable + ": " + person[temporaryVariable]);
      }
    }
    
    // Will output name: Adam, age: 34, job: Engineer on 3 separate lines
    

    for...of is a simpler way to loop over iterable data types like arrays, strings, maps, and sets and is similar to the python way of looping through iterables.

    const fruits = ["apple", "banana", "cherry"];
    for (const fruit of fruits) {
      console.log(fruit);
    }