Can You Tell a Forloop to Do the Last Iteration Again

JavaScript Loops Explained: For Loop, While Loop, Do...while Loop, and More

Loops are used in JavaScript to perform repeated tasks based on a condition. Weather condition typically return truthful or simulated. A loop will continue running until the defined condition returns false.

for Loop

Syntax

                for (initialization; condition; finalExpression) {   // code }                              

The for loop consists of 3 optional expressions, followed past a code block:

  • initialization - This expression runs earlier the execution of the beginning loop, and is usually used to create a counter.
  • condition - This expression is checked each time earlier the loop runs. If it evaluates to true, the argument or code in the loop is executed. If information technology evaluates to faux, the loop stops. And if this expression is omitted, it automatically evaluates to truthful.
  • finalExpression - This expression is executed after each iteration of the loop. This is usually used to increment a counter, only can be used to decrement a counter instead.

Whatsoever of these iii expressions or the the lawmaking in the code block can be omitted.

for loops are ordinarily used to run code a ready number of times. Also, you lot tin employ pause to go out the loop early, before the condition expression evaluates to false.

Examples

1. Iterate through integers from 0-viii:

                for (allow i = 0; i < ix; i++) {   console.log(i); }  // Output: // 0 // 1 // 2 // 3 // four // 5 // half dozen // 7 // 8              

two. Use break to leave out of a for loop earlier condition is false:

                for (allow i = i; i < ten; i += 2) {   if (i === 7) {     pause;   }   console.log('Total elephants: ' + i); }  // Output: // Total elephants: 1 // Total elephants: iii // Full elephants: 5              

Common Pitfall: Exceeding the Bounds of an Array

When iterating over an array, it'due south piece of cake to accidentally exceed the bounds of the array.

For case, your loop may endeavour to reference the quaternary chemical element of an assortment with merely 3 elements:

                const arr = [ ane, two, 3 ];  for (permit i = 0; i <= arr.length; i++) {   panel.log(arr[i]); }  // Output: // 1 // 2 // iii // undefined              

There are two ways to fix this code: set condition to either i < arr.length or i <= arr.length - ane.

for...in Loop

Syntax

                for (property in object) {   // lawmaking }              

The for...in loop iterates over the properties of an object. For each property, the code in the code block is executed.

Examples

1. Iterate over the properties of an object and log its proper name and value to the console:

                const capitals = {   a: "Athens",   b: "Belgrade",   c: "Cairo" };  for (allow key in capitals) {   console.log(key + ": " + capitals[key]); }  // Output: // a: Athens // b: Belgrade // c: Cairo                              

Common Pitfall: Unexpected Behavior When Iterating Over an Array

Though you can utilize a for...in loop to iterate over an assortment, information technology's recommended to use a regular for or for...of loop instead.

The for...in loop can iterate over arrays and array-similar objects, but it may non ever access array indexes in order.

Likewise, the for...in loop returns all properties and inherited properties for an array or assortment-like object, which tin can atomic number 82 to unexpected behavior.

For example, this uncomplicated loop works as expected:

                const array = [i, 2, 3];  for (const i in array) {   console.log(i); }  // 0 // one // ii                              

Simply if something similar a JS library yous're using modifies the Array prototype directly, a for...in loop volition iterate over that, too:

                const array = [1, ii, iii];  Array.epitome.someMethod = true;  for (const i in assortment) {   console.log(i); }  // 0 // 1 // 2 // someMethod                              

Though modifying read-just prototypes like Array or Object direct goes against best practices, it could exist an outcome with some libraries or codebases.

Also, since the for...in is meant for objects, it's much slower with arrays than other loops.

In short, just remember to just use for...in loops to iterate over objects, not arrays.

for...of Loop

Syntax

                for (variable of object) {   // code }                              

The for...of loop iterates over the values of many types of iterables, including arrays, and special collection types like Set and Map. For each value in the iterable object, the code in the code block is executed.

Examples

one. Iterate over an array:

                const arr = [ "Fred", "Tom", "Bob" ];  for (let i of arr) {   console.log(i); }  // Output: // Fred // Tom // Bob                              

ii. Iterate over a Map:

                const k = new Map(); m.ready(1, "black"); m.prepare(2, "cerise");  for (allow n of m) {   console.log(n); }  // Output: // [1, blackness] // [2, cherry]                              

3. Iterate over a Set:

                const s = new Gear up(); s.add(1); s.add("red");  for (let n of s) {   console.log(n); }  // Output: // 1 // cherry-red                              

while Loop

Syntax

                while (condition) {   // statement }                              

The while loop starts by evaluating condition. If condition evaluates to true, the lawmaking in the code block gets executed. If status evaluates to imitation, the code in the lawmaking block is not executed and the loop ends.

Examples:

  1. While a variable is less than ten, log it to the panel and increment it by one:
                allow i = one;  while (i < 10) {   panel.log(i);   i++; }  // Output: // 1 // ii // 3 // iv // 5 // 6 // vii // 8 // 9                              

practise...while loop

Syntax:

                do {   // argument } while (condition);                              

The do...while loop is closely related to while loop. In a practise...while loop, condition is checked at the end of each iteration of the loop, rather than at the outset before the loop runs.

This means that code in a practice...while loop is guaranteed to run at least once, fifty-fifty if the condition expression already evaluates to true.

Instance:

  1. While a variable is less than 10, log it to the panel and increment it by 1:
                let i = 1;  exercise {   console.log(i);   i++; } while (i < 10);  // Output: // 1 // 2 // 3 // iv // five // 6 // 7 // viii // 9                              

2. Push to an array, even if condition evaluates to true:

                const myArray = []; let i = 10;  practice {   myArray.push(i);   i++; } while (i < ten);  panel.log(myArray);  // Output: // [x]              

Acquire to code for gratuitous. freeCodeCamp's open source curriculum has helped more than 40,000 people go jobs as developers. Get started

mosiervered1965.blogspot.com

Source: https://www.freecodecamp.org/news/javascript-loops-explained-for-loop-for/

0 Response to "Can You Tell a Forloop to Do the Last Iteration Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel