liveBook · Manning

Hoisting

As explained in Secrets of the JavaScript Ninja, Second Edition

A common description of JavaScript declaration handling as moving declarations to the top of a scope, although declarations are registered before code executes rather than literally moved.

Hoisting is a handy shorthand, but declarations are not literally moved. JavaScript registers identifiers in lexical environments before executing code. section 5.5.3

Watch what happens when code runs:

  • A function declaration can be accessed before its position in the code; a function expression or arrow function cannot. section 5.5.3
  • A var declaration is registered, but its later assignment still runs during execution and can replace a function value. section 5.5.3
Listing 5.9. Accessing a function before its declaration
assert(typeof fun === "function",
  "fun is a function even though its definition isn't reached yet!");   #A

assert(typeof myFunExp === "undefined",                                 #B
  "But we cannot access function expressions");                         #B
                                                                        #B
assert(typeof myArrow === "undefined",                                  #B
  "Nor arrow functions");                                               #B

function fun(){}                                     #C
 
var myFunExpr = function(){};                        #D
var myArrow = (x) => x;                              #D

Compare access before a function declaration with access before function expressions and arrow functions. section 5.5.3

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains registration before execution and contrasts declaration forms, stopping short of further environment mechanics.
Examples
Compares early access to a function declaration with expressions and arrows, then shows a var assignment replacing a function.
What you can do after
Understand why declarations can be available before execution reaches them and why later assignments can change their values.
How it connects
Connects hoisting with lexical environments, scopes, function declarations, function expressions, and arrow functions.

Also explained in

Compare how 2 books explain hoisting →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.