nested loop in javascript

In JavaScript, you can use nested loops to iterate through multiple arrays or objects. The most common types of loops in JavaScript are the for loop and the while loop.

Here is an example of a nested for loop that will iterate through two arrays:

index.tsx
let array1 = [1, 2, 3];
let array2 = ['a', 'b', 'c'];

for (let i = 0; i < array1.length; i++) {
  for (let j = 0; j < array2.length; j++) {
    console.log(array1[i], array2[j]);
  }
}
186 chars
9 lines

This code will output:

index.tsx
1 a
1 b
1 c
2 a
2 b
2 c
3 a
3 b
3 c
36 chars
10 lines

Here is an example of a nested while loop that will iterate through an object:

index.tsx
let obj = {
  name: 'John',
  age: 30,
  email: 'john@example.com'
};

let keys = Object.keys(obj);
let i = 0;

while (i < keys.length) {
  let key = keys[i];
  console.log(`${key}: ${obj[key]}`);
  
  if (typeof obj[key] === 'object') {
    let nestedKeys = Object.keys(obj[key]);
    let j = 0;
    
    while (j < nestedKeys.length) {
      let nestedKey = nestedKeys[j];
      console.log(`${key}.${nestedKey}: ${obj[key][nestedKey]}`);
      j++;
    }
  }
  
  i++;
}
474 chars
27 lines

This code will output:

index.tsx
name: John
age: 30
email: john@example.com
43 chars
4 lines

gistlibby LogSnag