Skip to content Skip to sidebar Skip to footer

What Is Wrong With the Code if Something Keeps Looping Over and Over Again and You Closed It

Loops are used in JavaScript to perform repeated tasks based on a condition. Conditions typically return true or fake. A loop will go on running until the defined status returns false.

for Loop

Syntax

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

The for loop consists of three optional expressions, followed by a code block:

  • initialization - This expression runs before the execution of the first loop, and is unremarkably used to create a counter.
  • condition - This expression is checked each time before the loop runs. If it evaluates to true, the statement or lawmaking in the loop is executed. If it evaluates to faux, the loop stops. And if this expression is omitted, it automatically evaluates to true.
  • finalExpression - This expression is executed after each iteration of the loop. This is usually used to increment a counter, but can be used to decrement a counter instead.

Any of these three expressions or the the code in the code cake can be omitted.

for loops are normally used to run code a set number of times. Also, yous tin use intermission to go out the loop early, earlier the condition expression evaluates to simulated.

Examples

one. Iterate through integers from 0-viii:

                for (let i = 0; i < ix; i++) {   console.log(i); }  // Output: // 0 // 1 // 2 // 3 // 4 // 5 // 6 // 7 // 8              

two. Use break to exit out of a for loop before condition is fake:

                for (let i = 1; i < 10; i += 2) {   if (i === 7) {     pause;   }   panel.log('Total elephants: ' + i); }  // Output: // Total elephants: 1 // Total elephants: 3 // Total elephants: 5              

Common Pitfall: Exceeding the Bounds of an Array

When iterating over an assortment, it's easy to accidentally exceed the bounds of the assortment.

For example, your loop may try to reference the 4th element of an array with simply 3 elements:

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

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

for...in Loop

Syntax

                for (property in object) {   // code }              

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

Examples

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

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

Mutual Pitfall: Unexpected Beliefs When Iterating Over an Array

Though y'all tin use a for...in loop to iterate over an array, it's recommended to employ a regular for or for...of loop instead.

The for...in loop can iterate over arrays and array-like objects, just it may non always admission assortment indexes in order.

Also, the for...in loop returns all properties and inherited backdrop for an array or array-like object, which tin pb to unexpected behavior.

For example, this uncomplicated loop works as expected:

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

Just if something like a JS library yous're using modifies the Assortment image straight, a for...in loop will iterate over that, too:

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

Though modifying read-only prototypes like Assortment or Object direct goes against best practices, it could be an event with some libraries or codebases.

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

In short, but call back to only apply for...in loops to iterate over objects, non 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 Ready and Map. For each value in the iterable object, the lawmaking 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 m = new Map(); m.set(one, "black"); m.fix(ii, "red");  for (let north of m) {   console.log(north); }  // Output: // [1, black] // [2, cerise]                              

3. Iterate over a Set:

                const s = new Set(); southward.add(ane); s.add("red");  for (let northward of south) {   console.log(north); }  // Output: // 1 // blood-red                              

while Loop

Syntax

                while (condition) {   // statement }                              

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

Examples:

  1. While a variable is less than 10, log it to the console and increment information technology by 1:
                let i = 1;  while (i < 10) {   console.log(i);   i++; }  // Output: // ane // two // 3 // 4 // 5 // 6 // 7 // 8 // 9                              

do...while loop

Syntax:

                do {   // statement } while (condition);                              

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

This means that lawmaking in a do...while loop is guaranteed to run at least once, even if the condition expression already evaluates to true.

Case:

  1. While a variable is less than ten, log it to the console and increment it by i:
                let i = i;  do {   console.log(i);   i++; } while (i < 10);  // Output: // 1 // two // iii // 4 // 5 // 6 // vii // viii // 9                              

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

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

Larn to lawmaking for free. freeCodeCamp's open source curriculum has helped more than than xl,000 people get jobs as developers. Become started

kelsoposinever1937.blogspot.com

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

Post a Comment for "What Is Wrong With the Code if Something Keeps Looping Over and Over Again and You Closed It"