DEV Community

Dahye Ji
Dahye Ji

Posted on

JavaScript Basic - loops, for loop, for in, for of, forEach, while...

Loops

Loops evaluate a condition. A true expression runs a code block. Loops repeat the process until the expression is false.

for loop

for loop is the most commonly used loop.

Syntax

for(initialisation; condition; update) {
  // body
  // code block to be ran
}
Enter fullscreen mode Exit fullscreen mode

Let’s learn the meaning of these parts by example. The loop below runs console.log(i) for i from 0 up to (but not including) 5:

for (let i = 0; i < 5; i++) { 
  // shows 0, then 1, then 2, then 3, then 4
  console.log(i)
}
Enter fullscreen mode Exit fullscreen mode

Let's check above code part by part.
initialisation => let i = 0
: This executes once upon entering the loop.
condition => i < 5
: Checked before every loop iteration. If false, the loop stops.
body(code block to be ran) => console.log(i)
: Runs again and again while the condition is truthy.
update(step) => i++
: Executes after the body on each iteration.

Inline variable declaration

The variable i is declared right in the loop. This is called an *“inline” variable * declaration. Such variables are visible only inside the loop.

for (let i = 0; i < 3; i++) {
  console.log(i); // 0, 1, 2
}
console.log(i); // error, no such variable
Enter fullscreen mode Exit fullscreen mode
let i = 0;

for (i = 0; i < 3; i++) { // use an existing variable
  console.log(i); // 0, 1, 2
}
console.log(i); // 3, visible, because declared outside of the loop
Enter fullscreen mode Exit fullscreen mode

Skipping parts

Any part of for can be skipped.
For example, we can omit begin if we don’t need to do anything at the loop start.

let i = 0; // we have i already declared and assigned
for (; i < 3; i++) { 
  // no need for "initialisation(begin)" so it can be done with ';'
  console.log(i); // 0, 1, 2
}
Enter fullscreen mode Exit fullscreen mode

update(step) also can be omitted.

let i = 0;
for (; i < 3;) {
  console.log( i++ );
}
// this makes the loop identical to while (i < 3).
Enter fullscreen mode Exit fullscreen mode

for in

Syntax

for (key in object) {
  // code block to be executed
}
Enter fullscreen mode Exit fullscreen mode

for in statement can also loops(interates) over the properties of an Array:

let array = [10, 20, 30, 40, 50];

for (let index in array) {
  console.log(array[index], index);
}
Enter fullscreen mode Exit fullscreen mode

for in statement loops(iterates) through the properties of an Object.

const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}
Enter fullscreen mode Exit fullscreen mode

for of

for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects.

let array = [10, 20, 30, 40, 50];

for (let value of array) {
  console.log(value);
}
Enter fullscreen mode Exit fullscreen mode

while

Syntax

while(expression) {
  //statement to execute
}
Enter fullscreen mode Exit fullscreen mode

While the condition is truthy, the code from the loop body is executed.
For instance, the loop below outputs score while score < 5

let score = 0;
while(score < 5) {
  console.log(score);
  score++;
}
// 0
// 1
// 2
// 3
// 4
// it runs while score < 5 is true and then exit the loop.

Enter fullscreen mode Exit fullscreen mode


As long as the expression is true, it will enter into the code block again and again. This loop will run as long as the expression is true.

A single execution of the loop body is called an iteration. The loop in the example above makes five iterations.
If i++ was missing from the example above, the loop would repeat (in theory) forever(infinitely) because i is 0 and it will never become lager than 5 since it doesn't increase.
Any expression or variable can be a loop condition, not just comparisons: the condition is evaluated and converted to a boolean by while.

let i = 5;
while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops
  alert( i );
  i--;
}
Enter fullscreen mode Exit fullscreen mode

do while

Syntax

do {
  // loop body
} while (condition);
Enter fullscreen mode Exit fullscreen mode

The loop will first execute the body, then check the condition, and, while it’s truthy, execute it again and again.

let i = 0;
do {
  alert( i );
  i++;
} while (i < 3);
Enter fullscreen mode Exit fullscreen mode

This form of syntax should only be used when you want the body of the loop to execute at least once regardless of the condition being truthy. (Usually, the other form is preferred which is while loop)

let value = 5;
do {
  console.log(value);
  value++;
} while(value < 3);
// this is false. because the value = 5 but it tells you to iterate while(value < 3). However, it will still print 5(because of do { console.log(value); }) and when it checks the condition - while(value < 3), it will exit the loop.
Enter fullscreen mode Exit fullscreen mode

forEach

let todos = ["clean room", "make lunch", "walk my dog", "study JS",]
todos.forEach(function(todo, i) {
  console.log(todo, i);
})
Enter fullscreen mode Exit fullscreen mode

Above code is the same as this code using for loop

for(let i=0; i < todos.length; i++) {
  console.log(todos[i], i);
}
Enter fullscreen mode Exit fullscreen mode

break

Breaking the loop
Normally, a loop exits when its condition becomes falsy but we can force the exit at any time using the special break directive.
For example, the loop below asks the user for a series of numbers, “breaking” when no number is entered

let sum = 0;

while (true) {
  let value = +prompt("Enter a number", '');
  if (!value) break; // if the user enters an empty line or cancels the input. It stops the loop immediately, passing control to the first line after the loop.
  sum += value;
}
alert('Sum: ' + sum);
Enter fullscreen mode Exit fullscreen mode

continue

The continue directive is a “lighter version” of break. It doesn’t stop the whole loop. Instead, it stops the current iteration and forces the loop to start a new one (if the condition allows).
We can use it if we’re done with the current iteration and would like to move on to the next one.

// The loop below uses continue to output only odd values.
for (let i = 0; i < 10; i++) {
  // if true, skip the remaining part of the body (so it doesn't console.log if it's even number)
  if (i % 2 == 0) continue;
  console.log(i); // 1, then 3, 5, 7, 9 (only console.log odd numbers)
}

Enter fullscreen mode Exit fullscreen mode

Discussion (0)