Languages
[Edit]
EN

JavaScript - loops: for, while, do while

4 points
Created by:
Kate_C
19790

In JavaScript there are available few kinds of loops.

1. for loop examples

1.1. Classic for loop example

// ONLINE-RUNNER:browser;

for (var i = 0; i < 5; ++i) {
    console.log(i);
}

1.2. Foreach loop (for...of loop) over array example

// ONLINE-RUNNER:browser;

let array = [1, 2, 3, 'text'];

for (let entry of array) {
    console.log(entry);
}

Note: this loop has been added in ECMAScript 2015 (6th Edition).

1.3. for...in loop over object example

// ONLINE-RUNNER:browser;

var object = {
    'key1' : {
        name : 'John',
        age : 43
    },
    'key2' : {
        name : 'Kate',
        age : 54
    },
    'key3' : {
        name : 'Diego',
        age : 21
    },
};

for (var key in object) {
    if (object.hasOwnProperty(key)) {
        var entry = object[key];

        console.log(key + ' : ' + entry.name + ', ' + entry.age);
    }
}

Note: for...in loop only iterates over enumerable and non-Symbol properties,

2. while loop example

// ONLINE-RUNNER:browser;

var value = 0;

while (value < 10) {
    value += 2;

    console.log(value);
}

3. do...while loop example

// ONLINE-RUNNER:browser;

var value = 0;

do {
    value += 2;

    console.log(value);
} while (value < 10);

4. break keyword with loop example

4.1. Classic for loop with beak operation example

// ONLINE-RUNNER:browser;

for (var i = 0; ; ++i) {
    if(i >= 5) {
        break;
    }

    console.log(i);
}

4.2. Foreach loop (for...of loop) over array with break operation example

// ONLINE-RUNNER:browser;

let array = [1, 2, 3, 'text'];

for (let entry of array) {
    if(entry == 3) {
        break;
    }

    console.log(entry);
}

Note: this loop has been added in ECMAScript 2015 (6th Edition).

4.3. for...in loop over object with break operation example

// ONLINE-RUNNER:browser;

var object = {
    'key1' : {
        name : 'John',
        age : 43
    },
    'key2' : {
        name : 'Kate',
        age : 54
    },
    'key3' : {
        name : 'Diego',
        age : 21
    },
};

for (var key in object) {
    if (key == 'key3') {
        break;
    }

    var entry = object[key];

    console.log(key + ' : ' + entry.name + ', ' + entry.age);
}

Merged questions

  1. js for
  2. javascript for
  3. js while
  4. javascript while
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

â€ïžđŸ’» 🙂

Join