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

virus200
virus200
6,583 Points

The order of JavaScript variables and functions

Generally programming code executes top to bottom unless conditionals or something come into play to change the execution order. It is said it is best practice to place variables at the top of code in JavaScript which means there may be a variable declared that calls a function that is declared later in the code. How does that variable call a function that hasn't been declared yet like from the code snippet from a lesson below?

var randomNumber = getRandomNumber(10);
var guess;
var guessCount = 0;

function getRandomNumber( upper ) {
  var num = Math.floor(Math.random() * upper) + 1; 
  return num;
}

1 Answer

function declarations are hoisted. Function expressions aren't. So, if you didn't want this to happen with your code you would rewrite the getRandomNumber function like this

var getRandomNumber = function( upper ) {
  var num = Math.floor(Math.random() * upper) + 1; 
  return num;
}

Get more info here

Let me know if this helps