Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 12, 2020 08:59 pm GMT

When to use the 'for' loop

Nope, not Froot Loops. That cereal is nasty.

I'm talking about JavaScript loops, and thank goodness for 'em!

Loops are something you should feel confident with when coding. You're going to need it, and you'll be using it more than you think. Without it, we'd all be writing lines and lines of repeated code, which totally goes against writing DRY code.

There are a few different loop statements to choose from, and depending on the data you're working with and what your main goal is, sometimes, it makes more sense to use one than the other.

To help start us off in this series, let's take a look at the for loop, the most common one in the bunch.

Structure

for (initialization; condition; iteration) {   loop body}
Enter fullscreen mode Exit fullscreen mode
  • initialization - Think of this as a counter. You give it a number to start with (you're initializing it).

  • condition - This is a logical statement that must return true in order for the loop body to execute, and it uses the current value in 'initialization' to determine if the condition is true or false.

  • loop body - This is the block of code that will run, but only if condition is true.

  • iteration - Once the loop body is done doing what it needs to do, iteration updates the counter/initialization value.

Example

You're helping create a grading app, and the feature you're working on allows teachers to select a few of the students' grades so extra credit can be added to it. The teacher should be able to input a score, and that score will be added to the selected grades.

function extraCredit(grades, extraCreditScore) {   for (let i = 0; i < grades.length; i++) {      grades[i] += extraCreditScore;   }   return grades;}const grades = [75, 90, 83, 87, 69, 72];const extraCreditScore = 5;const newGrades = extraCredit(grades, extraCreditScore);console.log(newGrades);
Enter fullscreen mode Exit fullscreen mode

Check out my Repl.it to see the code in action. Feel free to add the commented sections back in to see what's really happening as the loop body runs.

How it works

/* The `for` loop flow1. Initialization2. Condition3. Loop body4. Iteration5. Return to step 1, and repeat everything until condition becomes `false`.*/
Enter fullscreen mode Exit fullscreen mode

So what's happening exactly when the for loop runs?

Well, let's, first, take a look at our function extraCredit. It accepts two parameters that will be used in our loop:

  • grades - These are the grades that the teacher selected.

  • extraCreditScore - This is the extra credit score that was entered by the teacher.

What we're expecting to happen is that each element in grades will have the extraCreditScore added to it. The function will then return the array but with the updated grades.

When the function executes, the first thing that's looked at is let i = 0 (initialization), then i < grades.length (condition). This is basically saying, "We're starting at 75, the first element in grades (remember, arrays start with an index of 0). The length of grades is 6, so is 0 < 6?"

Ding, ding, ding! Our condition statement is true, which allows us to go into the loop body (grades[i] += extraCreditScore).

In the loop body, the value of i in grades[i] takes the current value of i in initialization (i = 0), so grades[0] == 75. The loop body is saying, "75 + 5(grades[0] + extraCreditScore), then reassign grades[0] with the updated grade, so now, grades[0] = 80."

Once that loop body is done running, our code goes back up to i++ (iteration). This is saying, "Increase the current value of i by 1."

Aaaand... we're back to initialization, but this time, i == 1. The flow, then, keeps repeating until condition returns false. When that happens, it exits the loop body, and our code moves on to return grades.

When to use it

Use this loop when you know exactly how many times you need the loop to run. This is why the for loop is often times used on arrays.

It uses the length of an array to tell it to loop x amount of times. Initialization keeps track of the element in the array (by index number) that is being "worked on." Loop body is what will update the value of the elem being worked on. And iteration keeps things moving along.

Whew - that was a lot! But I hope you now have a better understanding of how to use a for loop, what's happening while it's running, and when to use it.


Original Link: https://dev.to/ennalezah/when-to-use-the-for-loop-5em4

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To