JavaScript Loops
Loops have been an enemy of mine since I started my coding journey, the syntax itself threw me off and understanding each line of code proved to be challenging for me. In order to better understand loops I created this blog to break down each line of code in a simple way that anyone can understand it. (atleast I hope 😬)
For Loop:
A for loop repeats until a specified condition evaluates to false.
Code breakdown:
- First we initialize i to 0 (this is where the counter starts)
- The condition: Repeat this loop if the condition evaluates to TRUE, when i evaluates to FALSE and no longer is less than or equal to 5 terminate the loop.
- i is evaluated at the end of each loop iteration, this occurs BEFORE the next evaluation of condition.
- Code block(statement) This is what is executed as long as the condition evaluates to true. In this case I console.log(i).
For/in Loop:
A for/in statement iterates over enumerable, non-Symbol properties of an Object. For each distinct property, JS executes the specified statements.
Code breakdown:
- The variable key iterates over all the person object’s properties and returns an interpolated string that lists the property names and their values.
For/of Loop:
A for/of statement loops through the values of an iterable object including Arrays, strings, Maps, and more. Invoking a custom iteration hook with statements to be executed for the value of each distinct property.
Code breakdown:
- The iteration hook in this example is element, for every element inside of the fruits array, display the element to the console.
While Loop:
The while statement starts by evaluating the condition. If the condition is true, the code block is executed.
Code breakdown:
- First we create our count variable and initialize it to 0.
- While the condition of count is less than 10, is TRUE execute the code block, if FALSE the code block is not executed and the while loop ends.
- The count inside of the code block is incremented by 2.
Do/while Loop:
The do/while statement repeats until a specified condition evaluates to false.
Code breakdown:
- First we create our i variable and initialize it to 0.
- The code block inside is executed at least once before the condition is evaluated and is re-executed each time the condition evaluates to TRUE. In this code block i is declared to the value of i plus 1.
- Here the condition is a Boolean expression. If the Boolean expression evaluates to true, the statement is executed again. When the Boolean expression evaluates to false, the loop is terminated.