Loops offer a quick and easy way to do something repeatedly
The statements for loops provided in JavaScript are:
- for statement
- do...while statements
- while statements
- break statements
- continue statements
- for...in statements
- for...of statements
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
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)
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
}
Use the break statement to terminate a loop,
break [label]
for (var i = 0; i < a.length; i++) {
if (a[i] == theValue) {
break;
}
}
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);
}
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 (new in ES6) does use an object-specific iterator and loop over the values generated by that.
for (variable of object) { statement }
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"
}