Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - for loops

for

for loops loop thru a block of code n number of times.


// ITI = Initialize. Test, Increment
let output3 = "";
for (var i = 0; i < 5; i++)
{
    output3 += "The number is " + i + "
"; }

 

There is no for each in javascript - at least not any more. It was deprecated as of ES4. Use for in or for of instead.

Both for..of and for..in statements iterate over lists. The values which each iterate on are different though. See https://www.geeksforgeeks.org/htmlcollection-for-loop/.

 

for in

for..in returns a list of keys (indexes) on the object being iterated.


// for in demo. show the indexes
let colors = [ "Red", "Blue", "White", "Green" ];
let output = "";

for (let i in colors)
{
    output += i + "<br />";
}

 

for of

for of - loops through the values of an iterable object. for..of returns a list of values of the numeric properties of the object being iterated.


// show the values
let colors2 = ["Red", "Blue", "White", "Green"];
let output2 = "";

for (let i of colors2)
{
    output2 += i + "<br />";
}