For the More Curious: Hoisting

JavaScript was created so that nonprofessional programmers could create web content with some basic interactivity. Although the language has features intended to make code error-resistant, some of its features end up causing errors in practice. One of these features is hoisting.

When the JavaScript engine interprets your code, it finds all of the variable and function declarations and moves them to the top of the function they are in. (Or, if they are not in a function, they are evaluated before the rest of the code.)

This is best illustrated with an example. When you write this code:

function logSomeValues () {
  console.log(myVal);
  var myVal = 5;
  console.log(myVal);
}

it is interpreted as though ...

Get Front-End Web Development: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.