Loops: while and for
While writing a program, you can meet a situation when you need to execute an action repeatedly. In that case, you would need to write loop statements, which let us reduce the number of lines. In other words, loops offer a quick and easy way to do something repeatedly.
For example, if you want to type a ‘Welcome to Web’ message 100 times in your webpage, instead of copying and pasting the same line 100 times, you can use loops, you can complete this task in 3 or 4 lines.
There are five kinds of tools that JavaScript supports:
- while
- do…while
- for
- for…in
- for…of
Let’s discuss each of these loop statements in detail.
The “while” loop
The “while” loop is the most fundamental loop in JavaScript. The while loop executes its statement or code block repeatedly as long as a specified condition is true. Once the expression becomes false, the loop ends.
The syntax for while
while (condition) {
// code
// so-called "loop body"
}
The code from the loop body will be executed as soon as the condition is truthy. In the example below the loop outputs i while i < 10:
let i = 0;
while (i < 10) { // shows 0, then 1, then 2, … ,then 9
console.log(i);
i++;
}
There are three iterations (repeat) that loop makes in the example above. Iteration means a single execution of the loop body.
If i++ was missing from the presented above example, the loop would repeat forever. But the browser provides ways to stop such loops. Any variable or expression can be a loop, which is evaluated and converted to a boolean by while.
Example of a shorter way to write while (i != 0):
The “do…while” loop
The do...while loop has some similarities with while loop except that in do...while loop the block of code performed once even before checking the condition. It means that the do...while statement repeats until a specified condition evaluates to false.
We can move the condition check below the loop body using the do...while syntax:
do {
// loop body
} while (condition);
The loop will execute the body first, then after checking the condition will execute it again and again in case it is truthy.
For example:
You can use this form of syntax when you want the body of the loop to execute at least once nevertheless of the condition being truthy. Usually, the other form is preferred: while(…) {…}.
The “for” loop
The for loop repeats a block of code since a specified condition evaluates to false.
The for loop is used to execute a block of code for a certain number of times.
It is more complex, but also the most commonly used loop, which looks like this:
for (begin; condition; step) {
// ... loop body ...
}
The for loop is the most solid form of looping that includes the following three important parts:
- The loop initialization is used to initialize the counter variables and executed first even before the loop begins. It is used to assign values to variables that will be used inside the loop.
- The condition expression is evaluated at the beginning of every iteration. The loop statement executes if it evaluates to true, and the for loop ends if it evaluates to false.
- Increment is used to update the loop counter with a new value each time the loop runs.
The “for...in” loop
The for...in loop is a special type of a loop that iterates a specified variable over the properties of an object. JavaScript executes the specified statements for each distinct property.
for...in is a method that used for iterating over "enumerable" properties of an object and applies to all objects that have these properties.
An enumerable property is a property of an object that has an Enumerable value of true. So property is "enumerable", if it is enumerable. By calling property.enumerable we can see if a property is enumerable. It will return true or false.
The for...in loop is used with the following syntax :
Syntax:
for (variableName in Object) {
// Code to be executed
}
The variable in the for...in loop is not a number but string, which involves the name of the current property or the index of the current array element.
The "key" for value in an Array is the numerical index that is essentially enumerable properties.
This means that we can loop over all the values in an Array by bringing back their index using the for..in Array.
const arr = ['a', 'b', 'c', 'd'];
for (const index in arr) {
console.log(arr[index])
} // Result: a, b, c, d
But it is generally advised that for...in method can’t be used with arrays, because there is no guarantee that the iteration happens in sequence, which is usually important for arrays.
In this example, you can see how to loop through all properties of a JavaScript object. If we want to loop through and console.log all the values in this Object, we can do the following :
let obj = {
a: 'a',
b: 'b',
c: 'c',
d: 'd',
}
for (let key in obj) {
console.log(obj[key])
} // Result: a, b, c, d
The characters in a string have indexes. So the indexes are enumerable properties (like Arrays) that just happen to be integers.
let string = 'Welcome to Web';
for (let index in string) {
console.log(string[index])
} // Result: W, e, l, c, o, m, e, ,t, o, ,W, 3, D, o, c, s
The for...of Loop
The for...of statement creates a loop that allows it to iterate over arrays or other iterable objects (such as Arrays, Strings, Maps, Sets, and so on)very easily.
for...of method is used for iterating over "iterable collections" that are objects that have a [Symbol.iterator] property.
With a [Symbol.iterator] the property we can easily iterate over the collection by calling the [Symbol.iterator]().next() method to get back the next item in the collection.
The for...of syntax is wrapping around the [ [Symbol.iterator] to create loops and it uses the following syntax :
for (variable of iterable) {
// code block to be executed
}
let arr = ['a', 'b', 'c', 'd'];
for (let item of arr) {
console.log(item)
}
// Result: a, b, c, d
Example for of loop through strings:
for..of and Objects
The for...of loop does not work with Objects as they are not "iterable", that is why they do not have a [Symbol.iterator]property.
for..of and Arrays/Strings
The for...of loop works rather well with Arrays and Strings because they are iterable. This method is a good way of looping through an Array in sequence.
Example for of loop through arrays:
let string = 'Welcome to Web';
for (let the character of string) {
console.log(character)
} // Result: W, e, l, c, o, m, e, ,t, o, ,W, 3, D, o, c, s
Breaking the loop
When the condition of the loop becomes falsy it exits, but we can force the exit just using the special break directive.
In this example the loop asks the user for a series of numbers, “breaking” when no number is entered:
for (let i = 1; i <= 10; i++) {
if (i == 6) break;
console.log(i);
} // Result: 1, 2, 3, 4, 5
for (let i = 0; i < 5; i++) {
for (let j = 0; j < 5; j++) {
if (j === 2) {
i = 5;
break;
}
}
console.log(i);
} // Result: 5
Continue to the next iteration
We call the continue directive a “lighter version” of a break, which does not stop the whole loop. But it stops the current iteration and if the condition allows it forces the loop to start a new one.
The loop in this example uses continue to output only odd values:
for (let i = 1; i <= 10; i++) {
if (i % 2 == 0) continue;
console.log(i); // Result: 1, 3, 5, 7, 9
}
The continue directive stops executing the body for values of I and passes control to the next iteration of for. That is why the alert is only called for odd values.
The continue directive helps decrease nesting
A loop that shows odd values looks like this:
for (let i = 1; i <= 10; i++) {
if (i % 2) {
console.log(i); // Result: 1, 3, 5, 7, 9
}
}
This is identical to the example above from a technical point of view. We can just cover the code in an if block instead of using continue. But this created one more level of nesting. The long code inside of may decrease the readability.
No break/continue to the right side of ‘?’
So if we take this code:
if (i > 10) {
console.log(i);
} else {
continue;
}
…and rewrite it using a question mark, it will stop working: there will be a syntax error. It is another reason not to use the question, mark operator? instead of if.
(i > 10) ? console.log(i): continue; // continue isn't allowed here
0 Comments
CAN FEEDBACK
Emoji