JavaScript Loop

What is Loop?

Loops are used to run a block of statements over and over again with different value.

There are different kinds of loops

  • for: loops through a block of code for a number of times
  • for/of: loops through a block of code based on iterable objects
  • for/in: iterates over all enumerable properties of an object that are keyed by strings.
  • while: iterates while a condition is true.
  • do/while: iterates block of code once and then loops while the condition is true

for

Syntax:

for (initialization; condition; final-expression) {
code block
}

initialization An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.

condition An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true.

final-expression An expression to be evaluated at the end of each loop iteration.

Example

Following is an example which loops 8 times based on the condition 'i<9'.

var str = '';
for (let i = 1; i < 9; i++) {
str = str + i;
}

console.log(str);
// expected output: "12345678"

for..of loop

The for...of statement creates a loop iterating over iterable objects.

Syntax:

for (variable of iterable) {
code block
}

variable A different property is assigned to variable on each iteration.

object an Object whose iterable properties are iterated.

Example

Following is an example which loops prints all elements.


var object = [1, 2, 3];

for (const property of object) {
console.log(property);
}
// expected output:
// 1
// 2
// 3

for..in loop

Syntax:

for (variable in object) {
code block
}

variable A different property name is assigned to variable on each iteration.

object an object whose non-Symbol enumerable properties are iterated over.

Example

Following is an example which loops prints all property name.

var str = '';
var object = { a: 1, b: 2, c: 3 };

for (const property in object) {
console.log(property);
}
// expected output:
// "a"
// "b"
// "c"

while loop

Syntax:

while (condition) {
code block
}

Example

Following is an example which loops until i = 3.


var i =1;
while (i< 3) {
i++
console.log(i);
}
// expected output:
// 1
// 2

do..while loop

Syntax:

do {
code block
} while (condition)

Example

Following is an example which loops once and till condition is true.


var i = 1;
do {
console.log(i);
i++
} while (i< 1)
// expected output:
// 2