Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript Basics: The for loop

Wednesday, April 12, 2017

JavaScript Basics: The for loop

The for loop is a looping construct in JavaScript that are more simplistic than the while loop.   When writing the for loop there are three three parts they are

  1.  Initialize - a count variable is initialize, it's usually zero but it doesn't have to be
  2. Test - A test to see if the loop should continue
  3. Increment - finally the count is incremented, it doesn't have to be an increment it could be decrements as well

Let's use the JavaScript code to demonstrate:

If you execute the loop below you will bet a for loop that executes when i is less than 10

for (var i = 0; i < 10; i++)
    console.log("i is " + i);

console.log("i outside of for look is " + i);

Here is the output:

Noticed the number outside of the loop is bigger than the number that's inside the loop on the last execution.  Just keep that in mind when you are working with a for loop.  If you want to execute on the tenth loop you have to change your test condition to say i <= 10.  This implies that i has to be less than or equal to 10 before the loop stops executing

Here is the output:

Although the value outside of the loop is now 11!

No comments:

Post a Comment

Search This Blog