Skip to content

Latest commit

 

History

History
117 lines (97 loc) · 2.48 KB

loops.md

File metadata and controls

117 lines (97 loc) · 2.48 KB

Loops

Loops offer a quick and easy way to do something repeatedly

The statements for loops provided in JavaScript are:

  1. for statement
  2. do...while statements
  3. while statements
  4. break statements
  5. continue statements
  6. for...in statements
  7. for...of statements

for statement

A for loop repeats until a specified condition evaluates to false.

for ([initialExpression]; [condition]; [incrementExpression])
    statement
//example
    let arr = [];
    for(let i = 0; i < 5; i++) {
        arr.push(i);
    }
    console.log(arr) // 0, 1, 2, 3, 4

do...while statement

statement executes once before the condition is checked

do
    statement
while (condition);
//example
let i = 0;
do {
    i +=1;
    console.log(i); // 0, 1, 2, 3, 4
} while(i < 5)

while statement

A while statement executes its statements as long as a specified condition evaluates to true

while (condition)
    statement
//example
let a = 0;
while(a < 3) {
    ++a;
    console.log(a) // 1,2,3
}

break statement

Use the break statement to terminate a loop,

break [label]
for (var i = 0; i < a.length; i++) {
  if (a[i] == theValue) {
    break;
  }
}

continue statement

The continue statement can be used to restart a while, do-while, for or label statements

continue [label];
    var i = 0;
    var n = 0;
    while (i < 5) {
        i++;
        if (i == 3) {
             continue;
        }
     n += i;
     console.log(n);
}

for...in statement

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

for (variable in object) {
    statements
}

for...of statement

for...of (new in ES6) does use an object-specific iterator and loop over the values generated by that.

for (variable of object) { statement }

Differnce betwee for...in and for...of statements

for...in for...of
statements iterate over lists statements iterate over lists
for..in returns a list of keys on the object being iterated for..of returns a list of values of the numeric properties of the object being iterated.
//example
let list = [4, 5, 6];

for (let i in list) {
   console.log(i); // "0", "1", "2",
}

for (let i of list) {
   console.log(i); // "4", "5", "6"
}