The Basics Of JavaScript Variable Definitions & Hoisting

The Basics Of JavaScript Variable Definitions & HoistingI wrote this tutorial as an introduction to an often overlooked subject.

I can’t blame you, JavaScript is an accessible language — just pop open your text editor and you’re ready to start coding.

But JavaScript has traditionally been a language of many quirks, oddball features and inconsistencies.

Perhaps this article will be helpful to those who are completely new to the language.

JavaScript TeacherBlockedUnblockFollowFollowingFeb 9First things first.

Scope is simply the area enclosed by {} brackets.

There are 3 main types of scopes that provide distinct behavior: global scope, block scope and function scope.

Each scope expects different things and has unique rules when it comes to variable definitions.

Event callback functions technically follow the same rules as function scope, they just take the execution context with them to execute at a later time (when the event is completed.

)Before we can see what the actual differences are we need to take a look at some basic variable definition rules.

This way we won’t get mixed up later down the road when variable visibility is visualized later in this tutorial.

Variable DefinitionsCase-SensitivityLet’s just get this out of the way first.

Variable names are case-sensitive.

This means a and A are two different variables, regardless which keyword (var, let or const) that was used to define them:DefinitionsVariables can be defined using var, let or const keywords.

Of course, if you tried to refer to a variable that wasn’t defined anywhere, youwould generate a ReferenceError error ”variable name is not defined”:We have to start somewhere — so let’s use this setup to explore variable definitions using var keyword and hoisting.

Prior to let and const the traditional ES5 model allowed only var definitions:The variable is defined in global scope once, but it automatically becomes available for use in an inner block-scope.

This is just how global scope works.

Everything defined in global scope will be available anywhere in your program.

Hoisting is limited to variables defined using var keyword and function names.

Variables defined using let and const are not hoisted and their use remains limited only to the scope in which they were defined.

Likewise, variables defined in global scope will propagate to pretty much every other scope defined in global context, including block-level scope, for-loop scope, function-level scope, and event callback functions created using setTimeout, setInterval or addEventListener functions.

But what happens if we define a variable inside a block scope?Variable name is hoisted to global scope — you can use it there now.

Except that the value of the hoisted variable is now undefined — it did not retain its original value.

Only its definition was hoisted.

In other words, only its name.

Think of hoisting is like a safety feature.

But try not to rely on it when writing code.

It just prevents reference error bugs.

You may not retain the value of a hoisted variable in global scope, but you will still save your program from generating an error and halting execution flow.

Thankfully, hoisting in JavaScript is automatic.

When writing your program more than half of the time, you won’t even need to think about it.

Function Name HoistingHoisting also applies to function names.

But variable hoisting always takes precedence.

We’ll see how that works in this section.

You can call a function in your code, as long as it is defined at some point later:Note that the function was defined after it was called.

This is legal in JavaScript.

Just make sure you understand that it happened because of function name hoisting:It goes without saying if the function was already defined prior to being called, there’d be no hoisting and everything would still work as planned.

Unlike variables, functions don’t have a value.

They have a body that will beexecuted, when the function is called by its defined name.

However, it is possible to assign a function to a variable name:This valid JavaScript code will not produce a function redefinition error.

Thefunction will be simply overwritten by second definition.

Even though fun() was a function, when we created a new variable fun andassigned another function to it, we rewired the name of the original function.

Having said this, what do you think will happen if we call fun() at this pointWhich function body will be executed?The second one!You might think that the following code will produce a redefinition error:However, this is still perfectly valid code — no error is generated.

Whenever you have two function defined using function keyword and they happen to share the same name, the function that was defined last will take precedence.

In this case if you call fun(); the console will output the second message:This actually makes sense.

In following scenario variable name will take precedence over function definitions even if it was defined prior to the second function definition with the same name:And now let’s call fun() to see what happens in this case:But this time the output is:You can see the order in which JavaScript hoists variables and functions.

Functions are hoisted first.

Then variables.

Defining Variables Inside Function ScopeAt this point you might want to know that variables defined inside a function will be limited only to the scope of that function.

Trying to access them outside of the function will result in a reference error:.

. More details

Leave a Reply