Help to understand nested for loops

here is my code

let arr = ["a", "b", "c", "d"];

let size = 2;

let newArr =[  ];

let newArr2 = [  ];

for (let i =0 ;i < size;i++){

for (let j =0 ;j < size;j++){

newArr.push(arr[j]);

}

newArr2.push(newArr);}

console.log(newArr);

console.log(newArr2);

here is console result
[ ‘a’, ‘b’, ‘a’, ‘b’ ]
[ [ ‘a’, ‘b’, ‘a’, ‘b’ ], [ ‘a’, ‘b’, ‘a’, ‘b’ ] ]


the question is why newArr.push(arr[j]) excuted four times before newArr2.push(newArr) is excuted ??

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

1 Like

it executed twice - I suggest you look at the code execution with this tool so you can see what happens: Python Tutor code visualizer: Visualize code in Python, JavaScript, C, C++, and Java

1 Like

thank you that helped alot

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.