JavaScript Variable Scope and Hoisting Explained

»jan. 31 2013 102

In this post, we will learn JavaScript’s variable scope and hoisting and all the idiosyncrasies of both.

We must understand how variable scope and variable hoisting work in JavaScript, if want to understand JavaScript well. These concepts may seem straightforward; they are not. Some important subtleties exist that we must understand, if we want to thrive and excel as JavaScript developers.

  • Receive Updates

Variable Scope
A variable’s scope is the context in which the variable exists. The scope specifies from where you can access a variable and whether you have access to the variable in that context.

Bov Academy

of Programming and Futuristic Engineering

A Once-in-a-Lifetime Opportunity

Train to Become an Exceptional and Successful Developer

While Building Real-World Projects You Can Benefit from for Years

By the founder of JavaScriptIsSexy

Variables have either a local scope or a global scope.

Local Variables (Function-level scope)
Unlike most programming languages, JavaScript does not have block-level scope (variables scoped to surrounding curly brackets); instead, JavaScript has function-level scope. Variables declared within a function are local variables and are only accessible within that function or by functions inside that function. See my post on Closures for more on accessing variables in outer functions from inner functions.
Continue Reading