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

Ordering the code

I try and do my best and emulate how Dave orders the code. In this case, putting the function before the loop instead of vice versa. Pardon me if I missed it but I don't recall him stating if the order of the code is important. 2 part question: 1) What are the minimum code elements that must exist in order for a loop to work properly 2) Can the loop be coded before the function? My guess for the second part is no but I just wanted to be sure.

2 Answers

Hi Ricardo,

These are good questions

For a loop to work properly, variables, constants, function expressions, objects, arrays, and any arguments passed to the loop's outer scope must be declared before the loop if not within the loop's inner scope. A function declaration, however, can be declared after or before the loop, because in either case it is hoisted to the top of the loop's outer scope (before the loop). The exception to this is when we pass arguments to a function closure that contains the loop: the arguments can be delcared after the function closure, but not after the fuction closure is called.

In short, in some cases, you can use a loop as the first line of code:

// this works as the first line of code because the number1 function declaration 
// is hoisted before the loop
while (number1() === 4) {
  if (true) { 
    break;
  }
}

function number1() {
  return 4
}
// this doesn't work as the first line of code because the number2 function expression 
// must be declared before the loop
while (number2() === 4) {
  if (true) { 
    break;
  }
}

var number2 = function() {
  return 4
}
// this works as the first line of code because the value x is declared 
// as number3 before this function closure is executed with number3 
// as the argument for x
function closure(x) {
  while (x() === 4) {
    if (true) {
      break;
    }
  }
}

var number3 = function() {
  return 4
}
closure(number3)

recommended resources:

Thank you Abraham...I appreciate your thorough response...I did notice that one of your recommended resources was the "Understanding closures in JavaScript" course which I will taking later on in my Full Stack JavaScript track