Lessons · JavaScript · reading a name before it exists
What exists before its line
Function declarations are hoisted whole, so you can call them above their definition. var is hoisted as undefined. let and const are hoisted but unusable before their line.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Code that calls a helper defined further down works because of hoisting; code that reads a let too early throws. Knowing which is which explains both.
How to think about it
Declare before use anyway; hoisting is a fact to understand, not a style to rely on. When a ReferenceError mentions a variable that exists, look for a use above its let.
Worked example
console.log(hi());hi: function declarations are hoisted whole, so calling above works.
function hi() { return "hi"; }The declaration, below the call.console.log(typeof later);undefined: var is hoisted without its value.
var later = 1;The value arrives here.
try { early; } catch (e) { console.log(e.name); }ReferenceError: let is hoisted but unusable before its line, the temporal dead zone.let early = 2;Now it exists.
Your turn
A helper that can be called from above.
helper() { return 1; }Solve one with the tests running
The trap
const f = function () {} is not hoisted as a function: the name is, the value is not, so calling f() above it throws.