JavaScript

JavaScript

JavaScript Loops:

Loops:

Loops are handy, if you want to run the same code over and over again, each time with a different value.

For example:

var fruits=["Apple","Banana","Kiwi","Pineapple"]
for(i=0;i<fruits.length;i++)
{
    console.log(fruits[i])
}

JavaScript Loop:

JavaScript supports different kinds of loops:

  • for loop
  • for/in loop
  • for/of loop
  • for/each loop

    for loop:

    A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop.

Syntax:

for ([initialExpression]; [conditionExpression]; [incrementExpression])
{
  statement
}

Example:

const cars = ["BMW", "Volvo", "Saab", "Ford"]
for(i=0;i<cars.length;i++)
{
    console.log(cars[i])
}

for/in loop:

The for/in statement iterates a specified variable over all the enumerable properties of an object. For each distinct property, JavaScript executes the specified statements.

Example:

 const cars = ["BMW", "Volvo", "Saab", "Ford"]
for(var car in cars)
{
    console.log(car)
}

for/of loop:

The for/of statement creates a loop Iterating over iterable objects (including Array, Map, Set, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.

Example:

const cars = ["BMW", "Volvo", "Saab", "Ford"]
for(var car of cars)
{
    console.log(car+" I Use")
}

for/each loop:

forEach() calls a provided callbackFn function once for each element in an array in ascending index order. It is not invoked for index properties that have been deleted or are uninitialized.

callbackFn is invoked with three arguments:

  • The value of the element.
  • The index of the element.
  • The Array object being traversed.

Example:

const cars = ["BMW", "Volvo", "Saab", "Ford"]
cars.forEach(function(car))
{
    console.log(car)
}