JavaScript Basic - loops, for loop, for in, for of, forEach, while...
Tags: javascript, loop, forloop, foreach
Published: 2021-12-01 13:33:44


#Loops
Loops evaluate a condition. A true expression runs a code block. <u>Loops repeat the process until the expression is false</u>.

#for loop
for loop is the most commonly used loop.
###Syntax
```js
for(initialisation; condition; update) {
  // body
  // code block to be ran
}
```

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:

```js
for (let i = 0; i < 5; i++) { 
  // shows 0, then 1, then 2, then 3, then 4
  console.log(i)
}
```
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 <u>visible only inside the loop</u>.
```js
for (let i = 0; i < 3; i++) {
  console.log(i); // 0, 1, 2
}
console.log(i); // error, no such variable
```

```js
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
```
##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.
```js
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
}
```
update(step) also can be omitted.
```js
let i = 0;
for (; i < 3;) {
  console.log( i++ );
}
// this makes the loop identical to while (i < 3).
```

#for in
###Syntax
```js
for (key in object) {
  // code block to be executed
}
```
for in statement can also loops(interates) over the properties of an Array:
```js
let array = [10, 20, 30, 40, 50];

for (let index in array) {
  console.log(array[index], index);
}
```
for in statement loops(iterates) through the properties of an Object.
```js
const object = { a: 1, b: 2, c: 3 };

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

#for of
for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects.
```js
let array = [10, 20, 30, 40, 50];

for (let value of array) {
  console.log(value);
}
```

#while
###Syntax
```js
while(expression) {
  //statement to execute
}
```
**While the condition is truthy**, the <u>code from the loop body is executed</u>.
For instance, the loop below outputs score while score < 5
```js
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.

```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 <u>condition is evaluated and converted to a boolean by while</u>.
```js
let i = 5;
while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops
  alert( i );
  i--;
}
```

#do while
###Syntax
```js
do {
  // loop body
} while (condition);
```
The loop will first execute the body, then check the condition, and, while it’s truthy, execute it again and again.
```js
let i = 0;
do {
  alert( i );
  i++;
} while (i < 3);
```
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)

```js
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.
```

#forEach
```js
let todos = ["clean room", "make lunch", "walk my dog", "study JS",]
todos.forEach(function(todo, i) {
  console.log(todo, i);
})
```
Above code is the same as this code using for loop
```js
for(let i=0; i < todos.length; i++) {
  console.log(todos[i], i);
}
```


#break
Breaking the loop
Normally, a loop exits when its condition becomes falsy but we can **force the exit at any time** <u>using the special break</u> directive.
For example, the loop below asks the user for a series of numbers, “breaking” when no number is entered
```js
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);
```

#continue
The continue directive is a “lighter version” of break. <strong>It doesn’t stop the whole loop</strong>. Instead, <u>it stops the current iteration</u> and <u>forces the loop to start a new one</u> (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. 
```js
// 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)
}

```