Loop in Js

Yoseob Shin·2022년 3월 29일
0

javascript

목록 보기
10/24
post-thumbnail

A loop is a programming tool that repeats a set of instructions until a specified condition, called a stopping condition is reached.

When we need to reuse a task in our code, we often bundle that action in a function. Similarly, when we see that a process has to repeat multiple times in a row, we write a loop. Loops allow us to create efficient code that automates processes to make scalable, manageable programs.

A for loop contains three expressions separated by ; inside the parentheses:

  • an initialization starts the loop and can also be used to declare the iterator variable.
  • a stopping condition is the condition that the iterator variable is evaluated against— if the condition evaluates to true the code block will run, and if it evaluates to false the code will stop.
  • an iteration statement is used to update the iterator variable on each loop.

for loop

The typical for loop includes an iterator variable that usually appears in all three expressions. The iterator variable is initialized, checked against the stopping condition, and assigned a new value on each loop iteration. Iterator variables can have any name, but it’s best practice to use a descriptive variable name.

for (let counter = 0; counter < 4; counter++) {
  console.log(counter);
}
  • The initialization is let counter = 0, so the loop will start counting at 0.
  • The stopping condition is counter < 4, meaning the loop will run as long as the iterator variable, counter, is less than 4.
  • The iteration statement is counter++. This means after each loop, the value of counter will increase by 1. For the first iteration counter will equal 0, for the second iteration counter will equal 1, and so on.
  • The code block is inside of the curly braces, console.log(counter), will execute until the condition evaluates to false. The condition will be false when counter is greater than or equal to 4 — the point that the condition becomes false is sometimes called the stop condition.

###Looping in Reverse
What if we want the for loop to log 3, 2, 1, and then 0? With simple modifications to the expressions, we can make our loop run backward!

To run a backward for loop, we must:

  • Set the iterator variable to the highest desired value in the initialization expression.
  • Set the stopping condition for when the iterator variable is less than the desired amount.
  • The iterator should decrease in intervals after each iteration.
// The loop below loops from 0 to 3. Edit it to loop backwards from 3 to 0
for (let counter = 3; counter >= 0; counter--){
  console.log(counter);
}

Looping through Arrays

for loops are very handy for iterating over data structures. For example, we can use a for loop to perform the same operation on each element on an array.

To loop through each element in an array, a for loop should use the array’s .length property in its condition.

const animals = ['Grizzly Bear', 'Sloth', 'Sea Lion'];
for (let i = 0; i < animals.length; i++){
  console.log(animals[i]);
}

Remember that arrays are zero-indexed, the index of the last element of an array is equivalent to the length of that array minus 1. If we tried to access an element at the index of animals.length we will have gone too far!

Nested loop

When we have a loop running inside another loop, we call that a nested loop. One use for a nested for loop is to compare the elements in two arrays. For each round of the outer for loop, the inner for loop will run completely.

const myArray = [6, 19, 20];
const yourArray = [19, 81, 2];
for (let i = 0; i < myArray.length; i++) {
  for (let j = 0; j < yourArray.length; j++) {
    if (myArray[i] === yourArray[j]) {
      console.log('Both loops have the number: ' + yourArray[j])
    }
  }
};

For each element in the outer loop array, myArray, the inner loop will run in its entirety comparing the current element from the outer array, myArray[i], to each element in the inner array, yourArray[j]. When it finds a match, it prints a string to the console.

The While Loop

// A for loop that prints 1, 2, and 3
for (let counterOne = 1; counterOne < 4; counterOne++){
  console.log(counterOne);
}
 
// A while loop that prints 1, 2, and 3
let counterTwo = 1;
while (counterTwo < 4) {
  console.log(counterTwo);
  counterTwo++;
}
  • The counterTwo variable is declared before the loop. We can access it inside our while loop since it’s in the global scope.
  • We start our loop with the keyword while followed by our stopping condition, or test condition. This will be evaluated before each round of the loop. While the condition evaluates to true, the block will continue to run. Once it evaluates to false the loop will stop.
  • Next, we have our loop’s code block which prints counterTwo to the console and increments counterTwo.
  • If counterTow doesn't increment inside the while code block on each iteration, then it will cause infinite loop.

When to use while loop

So you may be wondering when to use a while loop! The syntax of a for loop is ideal when we know how many times the loop should run, but we don’t always know this in advance. Think of eating like a while loop: when you start taking bites, you don’t know the exact number you’ll need to become full. Rather you’ll eat while you’re hungry. In situations when we want a loop to execute an undetermined number of times, while loops are the best choice.

Do...While Statements

In some cases, you want a piece of code to run at least once and then loop based on a specific condition after its initial run. This is where the do...while statement comes in.

let countString = '';
let i = 0;
 
do {
  countString = countString + i;
  i++;
} while (i < 5);
 
console.log(countString);

First, the code block after the do keyword is executed once. Then the condition is evaluated. If the condition evaluates to true, the block will execute again. The looping stops when the condition evaluates to false.

The break Keyword

magine we’re looking to adopt a dog. We plan to go to the shelter every day for a year and then give up. But what if we meet our dream dog on day 65? We don’t want to keep going to the shelter for the next 300 days just because our original plan was to go for a whole year. In our code, when we want to stop a loop from continuing to execute even though the original stopping condition we wrote for our loop hasn’t been met, we can use the keyword break.

  • The break keyword allows programs to “break” out of the loop from within the loop’s block.
for (let i = 0; i < 99; i++) {
  if (i > 2 ) {
     break;
  }
  console.log('Banana.');
}
 
console.log('Orange you glad I broke out the loop!');

break statements can be especially helpful when we’re looping through large data structures! With breaks, we can add test conditions besides the stopping condition, and exit the loop when they’re met.

Review

  • Loops perform repetitive actions so we don’t have to code that process manually every time.
  • How to write for loops with an iterator variable that increments or decrements
  • How to use a for loop to iterate through an array
  • A nested for loop is a loop inside another loop
  • while loops allow for different types of stopping conditions(boolean)
  • Stopping conditions are crucial for avoiding infinite loops.
  • do...while loops run code at least once— only checking the stopping condition after the first execution
  • The break keyword allows programs to leave a loop during the execution of its block
  • continue ->
profile
coder for web development + noodler at programming synthesizers for sound design as hobbyist.

11개의 댓글

comment-user-thumbnail
2025년 5월 19일

This can be consequently lovely along with inventive. I merely enjoy your hues along with anyone becomes the idea inside snail mail are going to be cheerful. best online cannabis dispensary

답글 달기
comment-user-thumbnail
2025년 6월 12일

I am impressed. I don't think Ive met anyone who knows as much about this subject as you do. You are truly well informed and very intelligent. You wrote something that people could understand and made the subject intriguing for everyone. Really, great blog you have got here.国分寺 英語 アルバイト

답글 달기
comment-user-thumbnail
2025년 7월 12일

i really like this article please keep it up. olxtoto login i really like this article please keep it up. olxtoto login i really like this article please keep it up. beb toto i really like this article please keep it up. slot dana i really like this article please keep it up. koitoto i really like this article please keep it up. togel online

답글 달기
comment-user-thumbnail
2025년 7월 14일

I am very happy to discover your post as it will become on top in my collection of favorite blogs to visit. data toto macau Most of the time I don’t make comments on websites, but I'd like to say that this article really forced me to do so. Really nice post! casino online i really like this article please keep it up. pol88 very interesting keep posting. olxtoto i love reading this article so beautiful!!great job! bandar togel online i love reading this article so beautiful!!great job! situs toto 176 login alternatif

답글 달기
comment-user-thumbnail
2025년 7월 29일

This was really an interesting topic and I kinda agree with what you have mentioned here!

답글 달기
comment-user-thumbnail
2025년 8월 7일

Most of the time I don’t make comments on websites, but I'd like to say that this article really forced me to do so. Really nice posttoto slotolxtotoolxtotositus toto loginhptoto situsolxtoto

답글 달기
comment-user-thumbnail
2025년 8월 25일

Thanks for the blog post buddy! Keep them coming... Togel Online

bandar togel

situs slot

Rtp totoxl

답글 달기
comment-user-thumbnail
2025년 9월 7일

her in fact awesome blog page. her realy content rich and then a this fantastic profession. i prefer this unique.카드 현금화

답글 달기
comment-user-thumbnail
2025년 9월 14일

Thanks for sharing this valuable content. In my view, if all webmasters and bloggers made good content as you did, the web will be a lot more useful than ever before. SEMESTA666

Great post but I was wondering if you could write a little more on this subject? I’d be very thankful if you could elaborate a little bit further. Thanks in advance! PANDAWA88

Thank you for sharing a bunch of this quality contents, I have bookmarked your blog. Please also explore advice from my site. I will be back for more quality contents. AGENTOTOPLAY

I have seen some great stuff here. Worth bookmarking for revisiting. I surprise how much effort you put to create such a great informative website. Your work is truly appreciated around the clock and the globe. LAPAK77

It is the kind of information I have been trying to find. Thank you for writing this information. It has proved utmost beneficial for me. https://stanonline.org/

답글 달기
comment-user-thumbnail
2025년 9월 18일

[I’ve been surfing online more than 5 hours today, yet I never found any interesting article like yours without a doubt. It’s pretty worth enough for me. Thanks...](I’ve been surfing online more than 5 hours today, yet I never found any interesting article like yours without a doubt. It’s pretty worth enough for me. Thanks...)skyux exchange[Thanks for sharing this valuable content. In my view, if all webmasters and bloggers made good content as you did, the web will be a lot more useful than ever before.](situs toto slot)[https://soulestudio.es/koan-studio/](Great post but I was wondering if you could write a little more on this subject? I’d be very thankful if you could elaborate a little bit further. Thanks in advance!)basket168[Thank you for sharing a bunch of this quality contents, I have bookmarked your blog. Please also explore advice from my site. I will be back for more quality contents.](slot gacor)[https://www.heliosazoulay.com/](I have seen some great stuff here. Worth bookmarking for revisiting. I surprise how much effort you put to create such a great informative website. Your work is truly appreciated around the clock and the globe.)finnu

답글 달기