Skip to content

Instantly share code, notes, and snippets.

@aJanuary
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aJanuary/f48e806cf17047fb5252 to your computer and use it in GitHub Desktop.
Save aJanuary/f48e806cf17047fb5252 to your computer and use it in GitHub Desktop.
Let and variable hoisting

Variable hoisting is a topic that gets me unreasonably and disproportionally agitated, so I guess this post gives me another excuse to rant.

Variable hoisting isn't a thing. At least not in the sense that there's specific code in a javascript compiler that's re-writing all of your functions so the variable declarations are at the top.

Its a name given to an artefact of lexical scoping. All lexically scoped languages exhibit the exact same behaviour. But I've only ever seen the term used when talking about javascript, and there are lots of articles out there about it.

Why? Because of the way it interacts with undefined variables. In most of the other languages (anyone know of an exception?), if you try to reference the variable before its been declared (or definitely assigned a value), you'll get an error. For statically compiled languages, that will tend to be a compiler error, for the rest it will be an exception or other runtime error indicator. In javascript, all variables will dereference to undefined before they are assigned a value, whether they are ever declared or not.

The let feature in ES6 brings javascript in line with other lexically scoped languages. You can't reference a variable before its been declared. I'm certain that as adoption of let grows, we'll see the term 'variable hoisting' all but disappear.

The post is wrong. The let feature doesn't mean typeof can now throw, because typeof is never being evaluated. The runtime is throwing a reference error before it even bothers trying to pass the variable through to typeof.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment