Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Object-Oriented JavaScript: Challenge Building Constructor Methods and Generating Objects createSpaces() Method Solution

Frank keane
Frank keane
8,074 Points

Why declare const inside for loop?

Hi. Wondering why the column variable declaration is inside the loop, I would have thought it would be reset each with iteration back to 'const = [];' Is that not emptying it? Obviously not but...?

Thanks

Mark Casavantes
Mark Casavantes
2,880 Points

Hello Frank,

Please post your code. I would not define my const variables inside a loop. const variables do not get emptied. If you are modifying your array, use "let" instead of "const".

I hope this is helpful.

3 Answers

Mark Wood's answer is correct, but I'll try to provide a little more detail. Frank, you are correct that the array is getting reset with each iteration of the loop, but keep in mind that there are 2 loops, and this is happening in the outer loop. The inner loop is filling up the array, and then the filled array is added to the spaces array via the push() method. At that point, we iterate into the outer loop, which resets the array. We aren't concerned about losing the contents of the array, as we no longer need the values because they're safely tucked away in the spaces array. When we've gone through all the columns and all the rows, the spaces array gets returned.

Joe Elliot
Joe Elliot
5,330 Points

Very well explained, thanks Jason.

Mark Wood
seal-mask
.a{fill-rule:evenodd;}techdegree
Mark Wood
Full Stack JavaScript Techdegree Student 11,100 Points

With each iteration of the 'x' loop, a new column array is created, which is then pushed to the spaces array. The final spaces array that's returned will have 7 column arrays inside it.

Crystal Vesely
Crystal Vesely
14,391 Points

Hello, can I ask why we are using const in the nested loop? I am trying to understand let and const better. From what I understand about the outer loop, using const for the array is being reset on every iteration. Is the same thing happening in the nested loop? Are variables always reset when the loop starts its next iteration?