Saturday, November 17, 2018

JavaScript For Loop

JavaScript Loops

Loops are handy, if you want to run the same code over and over again, each time with a different value.
Often this is the case when working with arrays:

Instead of writing:


text += cars[0] + "<br>"
text += cars[1] + "<br>"
text += cars[2] + "<br>"
text += cars[3] + "<br>"
text += cars[4] + "<br>"
text += cars[5] + "<br>";

You can write:


var i;
for (i = 0; i < cars.length; i++) { 
    text += cars[i] + "<br>";
}



Different Kinds of Loops

JavaScript supports different kinds of loops:
  • for - loops through a block of code a number of times
  • for/in - loops through the properties of an object
  • while - loops through a block of code while a specified condition is true
  • do/while - also loops through a block of code while a specified condition is true

The For Loop

The for loop has the following syntax:
for (statement 1; statement 2; statement 3) {
    code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.

for (i = 0; i < 5; i++) {
    text += "The number is " + i + "<br>";
}

Statement 1

Normally you will use statement 1 to initialize the variable used in the loop (i = 0).
This is not always the case, JavaScript doesn't care. Statement 1 is optional.
You can initiate many values in statement 1 (separated by comma):

for (i = 0, len = cars.length, text = ""; i < len; i++) { 
    text += cars[i] + "<br>";
}

var i = 2;
var len = cars.length;
var text = "";
for (; i < len; i++) { 
    text += cars[i] + "<br>";
}


Statement 2

Often statement 2 is used to evaluate the condition of the initial variable.
This is not always the case, JavaScript doesn't care. Statement 2 is also optional.
If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. Read about breaks in a later chapter of this tutorial.

The For/In Loop

The JavaScript for/in statement loops through the properties of an object:



var person = {fname:"John", lname:"Doe", age:25}; 

var text = "";
var x;
for (x in person) {
    text += person[x];
}






Share:

Related Posts:

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *

Popular Posts

Blog Archive

Blog Archive

Hassan.mosmer1@gmail.com