Learn JS #23

JavaScript For Loop


Loops can execute a block of code a number of times.


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:

for (let 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
  • for/of – loops through the values of an iterable 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.

Example

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

From the example above, you can read:

Statement 1 sets a variable before the loop starts (let i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5).

Statement 3 increases a value (i++) each time the code block in the loop has been executed.


Statement 1

Normally you will use statement 1 to initialize the variable used in the loop (let 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):

Example

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

And you can omit statement 1 (like when your values are set before the loop starts):

Example

let i = 2;
let len = cars.length;
let 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.


Statement 3

Often statement 3 increments the value of the initial variable.

This is not always the case, JavaScript doesn’t care, and statement 3 is optional.

Statement 3 can do anything like negative increment (i–), positive increment (i = i + 15), or anything else.

Statement 3 can also be omitted (like when you increment your values inside the loop):

Example

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

Loop Scope

Using var in a loop:

Example

var i = 5;

for (var i = 0; i < 10; i++) {
  // some code
}

// Here i is 10

Using let in a loop:

Example

let i = 5;

for (let i = 0; i < 10; i++) {
  // some code
}

// Here i is 5

In the first example, using var, the variable declared in the loop redeclares the variable outside the loop.

In the second example, using let, the variable declared in the loop does not redeclare the variable outside the loop.

When let is used to declare the i variable in a loop, the i variable will only be visible within the loop.

Categories

217 Responses

  1. Hello bro!301 Moved Permanently…
    дом престарелых в Ростове-на-Дону
    https://pansionat-rnd.ru/
    “Дом престарелых” (больница для престарелых) – это медицинское учреждение, которое предоставляет круглосуточную медицинскую и социальную помощь для престарелых людей, которые не могут жить независимо. В доме престарелых может быть оказана медицинская помощь, реабилитация, питание, гигиеническая и психологическая помощь и другие услуги.
    частный пансионат

    http://images.google.am/url?q=https://pansionat-rnd.ru/ http://images.google.com.kw/url?q=https://pansionat-rnd.ru/ http://www.google.is/url?q=https://pansionat-rnd.ru/ http://images.google.cat/url?q=https://pansionat-rnd.ru/ http://www.google.com.mt/url?q=https://pansionat-rnd.ru/

  2. drug information and news for professionals and consumers. All trends of medicament.
    ivermectin 50 mg
    Long-Term Effects. Prescription Drug Information, Interactions & Side.

  3. Comprehensive side effect and adverse reaction information. Comprehensive side effect and adverse reaction information.
    https://stromectolst.com/# stromectol uk
    Definitive journal of drugs and therapeutics. earch our drug database.

  4. Some are medicines that help people when doctors prescribe. Prescription Drug Information, Interactions & Side.
    https://nexium.top/# where to buy nexium without prescription
    Top 100 Searched Drugs. Medscape Drugs & Diseases.

  5. Everything what you want to know about pills. Prescription Drug Information, Interactions & Side.
    https://azithromycins.com/ generic zithromax medicine
    safe and effective drugs are available. All trends of medicament.

  6. Learn about the side effects, dosages, and interactions. Everything about medicine.
    new ed drugs
    Everything what you want to know about pills. Best and news about drug.

  7. Prescription Drug Information, Interactions & Side. Some are medicines that help people when doctors prescribe.
    https://canadianfast.online/# ed meds online without doctor prescription
    п»їMedicament prescribing information. Comprehensive side effect and adverse reaction information.

Leave a Reply

Your email address will not be published. Required fields are marked *