Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Gareth Redfern
36,217 PointsCreating Dynamic Variables Using A For Loop In Javasript
I am trying to use a for loop to create a dynamic set of variables but I am not sure how to do it. Here is my code:
var articlesLength = $('.training__article').length;
for (var i = 0; i <= articlesLength; ++i) {
var slide[i] = -( (slideWidth * i) - startPos);
}
I could drop the var from var slide[i]
and it would work but then the variables would be in global scope which is not good.
2 Answers

Dave McFarland
Treehouse TeacherHi Gareth Redfern ,
James Andrews is right. var
re-declares the variable each time through the loop. But, even with var
the slide
variable is in global scope. JavaScript only has a notion of "function scope," that is variables are only scoped within functions, not within braces like in some other languages.
Where are you using the slide
variable, and why do you need to keep it out of global scope? If you're using slide
in a self-contained function (that is, you don't need to use slide
in a bunch of different places) you could just put the code into a function and use slide
there:
function useSlide() {
var articlesLength = $('.training__article').length;
var slide = [];
for (var i = 0; i <= articlesLength; i += 1) {
slide[i] = -( (slideWidth * i) - startPos);
}
// do something with the slide array here
}
useSlide();

James Andrews
7,233 PointsThe problem is the var slide, because every time you go through the loop you are redeclaring the slide variable. if you want it not global put the whole thing in a function and call the function
Gareth Redfern
36,217 PointsGareth Redfern
36,217 PointsHi Dave, thank you for the clarification to James Andrews comment very helpful.