Try the Javascript Course for Free!

The FOR Loop in JavaScript- Tutorial

/ / JavaScript, Latest

The FOR Loop in JavaScript: Video Lesson

            This video lesson, titled “The FOR Loop,” shows you how to use the for Loop in JavaScript. This video is from our complete Introductory JavaScript tutorial, titled “Mastering Introductory JavaScript Made Easy v.1.0.”

The FOR Loop in JavaScript: Overview

            Loops are useful in JavaScript when you want to execute the same code over and over with a different value each time. The for loop in JavaScript is used to create a loop in JavaScript. The for Loop in JavaScript loops through a block of code a number of times. The for loop syntax is:

for (statement 1; statement 2; statement 3)
{the code block to be executed;}

The FOR Loop in JavaScript- Tutorial: A picture from "The FOR Loop" lesson within the "Mastering Introductory JavaScript Made Easy v.1.0" training interface.

The FOR Loop in JavaScript- Tutorial: A picture from “The FOR Loop” lesson within the “Mastering Introductory JavaScript Made Easy v.1.0” training interface.

            Each statement in the for loop in JavaScript sets a different parameter. Statement 1, the initialization statement, is executed before the code block, or loop, starts. You can initiate as many variables as you want in statement 1. Statement 2, the test statement, defines the condition for the loop to run. Statement 3, the iteration statement, is executed each time after the loop has been executed.

Example:
(if it was included in a script)
trees=[“Oak”,“Pine”,“Maple”,“Cherry”];for (var i=0,l=trees.length; i<l; i++){document.write(“Trees : “+ trees[i]+”<br>”);}
Explanation: Statement 1 sets the start variable “i” to zero and sets “l” to equal the length of the values of “trees”. Statement 2 sets the rule to display the list of values of “trees” starting at “0”, and Statement 3 sets the rule to increase one value each time the loop is executed (i++).
Result: Sets the for loop to display:Trees: OakTrees: PineTrees: Maple

Trees: Cherry

The FOR Loop in JavaScript: Instructions

  1. Type: for (a; b; c)

                        {d…;}

            Where “a” is the initialization statement, “b”, is the test statement, “c” is the iteration statement, and “d” is the code block to be executed.

TOP