Languages
[Edit]
EN

JavaScript - loops: for, while, do while

7 points
Created by:
Giles-Whittaker
739

In this article, we would like to show you a few kinds of loops available in JavaScript.

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 an 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 an 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

See also

  1. JavaScript - for, for-each and forEach performance test

Alternative titles

  1. js for loop
  2. js for, while, do while loop
  3. js while loop
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Statements & declarations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join