Basic Concept of a Loop
for (initialExpression; condition; updateExpression) {// for loop body: statement}
For Loops
for
for (let j = 0; j < 5; j++) {console.log(j)}/*** 0* 1* 2* 3*/
for loop syntax variations
I was debating adding the following variations for two reasons, primarily because I haven't seen them used often. Tow, they fall into the bucket of short hand which I heavely shy away from in development.
/****/for (let i = 0; i < 5; ) {console.log(i)i++}/****/for (let k = 0; ; ) {if (k > 3) breakconsole.log(k)k++}/****/for (let h = 0; ; h++) {if (h > 3) breakconsole.log(h)}/****/let a = 0for (; a < 5; a++) {console.log(a)}/****/let b = 0for (; ; b++) {if (b > 3) breakconsole.log(b)}/****/let l = 0for (; l < 3; ) {console.log(l)l++}/****/let t = 0for (; ; t++) {if (t > 3) breakconsole.log(t)}/****/let j = 0for (;;) {if (j > 3) breakconsole.log(j)j++}
for..in
💡 Do not use for in over an Array if the index order is important. It is better to use a for loop, a for of loop, or Array.forEach() when the order is important. - W3school
const object = { a: 1, b: 2, c: 3 }for (o in obj) {console.log(o)console.log(object[o])}/*** a,* 1,* b,* 2,* c,* 3**/
const arr = [1, 2, 3, 4]for (i in arr) {console.log(i)}/*** 0,* 1,* 2,* 3,*/
for (i in arr) {console.log(arr[i])}/*** a,* b,* c,* d,*/
for..of
for (a of arr) {console.log(a)}/*** a,* b,* c,* d*/
While
let a = 0while (a < 5) {console.log(a)a++}/*** 0,* 1,* 2,* 3,* 4*/