Tutorial by Examples

Standard usage for (var i = 0; i < 100; i++) { console.log(i); } Expected output: 0 1 ... 99 Multiple declarations Commonly used to cache the length of an array. var array = ['a', 'b', 'c']; for (var i = 0; i < array.length; i++) { console.log(array[i]); } Expect...
Standard While Loop A standard while loop will execute until the condition given is false: var i = 0; while (i < 100) { console.log(i); i++; } Expected output: 0 1 ... 99 Decremented loop var i = 100; while (i > 0) { console.log(i); i--; /* equivalent to i...
Breaking out of a while loop var i = 0; while(true) { i++; if(i === 42) { break; } } console.log(i); Expected output: 42 Breaking out of a for loop var i; for(i = 0; i < 100; i++) { if(i === 42) { break; } } console.log(i); Expected o...
Continuing a "for" Loop When you put the continue keyword in a for loop, execution jumps to the update expression (i++ in the example): for (var i = 0; i < 3; i++) { if (i === 1) { continue; } console.log(i); } Expected output: 0 2 Continuing a While...
var availableName; do { availableName = getRandomName(); } while (isNameUsed(name)); A do while loop is guaranteed to run at least once as it's condition is only checked at the end of an iteration. A traditional while loop may run zero or more times as its condition is checked at the begin...
We can name our loops and break the specific one when necessary. outerloop: for (var i = 0;i<3;i++){ innerloup: for (var j = 0;j <3; j++){ console.log(i); console.log(j); if (j == 1){ break outerloop; } } } Output: 0 0...
Break and continue statements can be followed by an optional label which works like some kind of a goto statement, resumes execution from the label referenced position for(var i = 0; i < 5; i++){ nextLoop2Iteration: for(var j = 0; j < 5; j++){ if(i == j) break nextLoop2Iteration; ...
6 const iterable = [0, 1, 2]; for (let i of iterable) { console.log(i); } Expected output: 0 1 2 The advantages from the for...of loop are: This is the most concise, direct syntax yet for looping through array elements It avoids all the pitfalls of for...in Unlike forEach(), ...
Warning for...in is intended for iterating over object keys, not array indexes. Using it to loop through an array is generally discouraged. It also includes properties from the prototype, so it may be necessary to check if the key is within the object using hasOwnProperty. If any attributes in th...

Page 1 of 1