EN
JavaScript - loops: for, while, do while
7
points
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);
}