OneCompiler

Loops

Loops are used to perform iterations on a block of code based on a criteria.

1. for()

for is used to iterate a set of statements based on a condition for fixed number of times.

Syntax

for(Initialization; Condition; Increment/decrement) {  
//code  
} 

Example

console.log('simple for loop');
for(let i=1;i<=10;i++) {
  console.log(i);
}

Run here

2. for..in()

For..in loop is used to iterate over properties of an object.

Syntax

for(variable in Object) {  
//code  
}  

Example

let info = {
  name: "foo",
  id: 123
}

for (let x in info) {
  console.log(x); // prints keys of info which are name and id
}

Run here

3. for..of()

For..of loop is used to iterate over values of an iterable object.

Syntax

for(variable of iterable-Object) {  
//code  
} 

Example

let mobiles = [ "iPhone", "Samsung", "OnePlus", "Pixel"];
for(let mbl of mobiles) {  
    console.log(mbl);
} 

Run here

4. while()

while is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations is not known in advance.

Syntax

while(condition) {  
//code 
}  

Example

 console.log('simple while loop');
let i=1;
while(i<=10) {
  console.log(i);
  i++;
}

Run here

5. do-while()

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

Syntax

do {  
//code 
} while(condition); 

Example

 console.log('simple do-while loop');
let i=1;
do {
  console.log(i);
  i++;
} while(i<=10);

Run here