Understanding hoisting will help you organize your function scope. Just remember, variable declarations and function definitions are hoisted to the top. Variable definitions are not, even if you declare and define a variable on the same line. Also, a variable declaration lets the system know that the variable exists while definition assigns it a value.

function doTheThing() {

// ReferenceError: notDeclared is not defined

// Outputs: undefined
var definedLater;

definedLater = 'I am defined!'
// Outputs: 'I am defined!'

// Outputs: undefined
var definedSimulateneously = 'I am defined!'
// Outputs: 'I am defined!'

// Outputs: 'I did it!'

function doSomethingElse(){
console.log('I did it!');

// TypeError: undefined is not a function

var functionVar = function(){
console.log('I did it!');

To make things easier to read, declare all of your variables at the top of your function scope so it is clear which scope the variables are coming from. Define your variables before you need to use them. Define your functions at the bottom of your scope to keep them out of your way.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.