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

Gareth Redfern
Gareth Redfern
36,217 Points

Creating 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
STAFF
Dave McFarland
Treehouse Teacher

Hi 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();
Gareth Redfern
Gareth Redfern
36,217 Points

Hi Dave, thank you for the clarification to James Andrews comment very helpful.

The 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