DEV Community

matthewpmi
matthewpmi

Posted on

JavaScript Loops

Loops are used to execute a block of code multiple times while a condition remains true. If, for example, you wanted to log to the console every number from 1 to 100, you could use a loop instead of having to type out each number.

While Loops
While loops are created using the 'while' keyword followed by parenthesis containing a conditional statement. One of the value in the conditional statement must be a variable.

First the variable must be declared and assigned a value.
let i = 1;
The variable will be used in the conditional statement inside of parenthesis.
while (i <= 10){
After the parenthesis there will be a code block inside {} that will execute until the condition is false.
console.log(i);
There must be some sort of incrementation (or decrementation) applied to the variable in the condition so that the condition approaches becoming false.
i++;
}
Once the condition is false we will 'break out' of the while loop and it will stop executing.
let i =1;

while (i <= 10){
  console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

For Loops
For loops accomplish the same thing as while loops using different syntax. For loops are created using the 'for' keyword followed by parenthesis containing 3 expressions separated by semicolons. The first expression is initialization in which a counting variable is created. The second expression is the condition that must remain true the code block to execute. The final expression is the increment or decrement which will be applied to the counting variable.

for (let i = 10; i >=0; i--){
  console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

For in Loops
For in loops are different than for and while loops as they apply specifically to objects. for in loops are created using the 'for' keyword followed by parenthesis. Inside the parenthesis is a variable followed by the keyword 'in' and the name of the object that we are iterating over. The variable will represent each property inside the object allowing us to access every key and value pair.

let team = {
  name: 'Jets',
  city: 'New York',
  conference: 'AFC',
}
Enter fullscreen mode Exit fullscreen mode
for (let key in team){
  console.log(key, team[key])
}
Enter fullscreen mode Exit fullscreen mode

The code block inside {} will execute for each property in the team object. This code will log each key in the team object followed by the value located at each key in the team object.

Top comments (0)