Hoisting variables using the "var" keyword

zmiles17 profile image zmiles17 ・2 min read

If you read my most recent blog post, then you may have wondered why I forgot to discuss "var". That is because "var" is considered older syntax, but that doesn't mean it has become obsolete. It turns out that before JavaScript introduced ES6 syntax, "var" was the only way to declare variables. Most codebases probably still implement "var" and I believe it is important to understand what it does and how it works.

"var" works similarly to "let" except "let" is block scoped, which means it only exists within the block of code that it was created in. Whenever we use "var" to declare a variable, that variable is now hoisted. You may ask what does it mean to be hoisted? Simply put, hoisting means that variable declaration occurs before execution. Here's an example if my explanation wasn't clear.

So I made a function called "exampleVar" and it just has a for loop with nothing inside of it with a conditional if/else statement, which will log in the console based on whether or not "i" has been defined. If you notice, I have used var to declare "i" which will hoist that variable to be available inside of the containing function. In other words, the variable "i" is initialized at the top of "exampleVar", but its value is not assigned until the for loop. Now let's look at what happens if I use "let" instead of "var".

As you can see, the functions are practically identical except for how I declare "i". That's about all you need to know about using "var" and hoisting in JavaScript. It is generally good practice to avoid using "var", since you can run into issues and bugs much easier than if you were using "const" or "let".

Posted on by:


markdown guide

Bit of clarification:
"Simply put, hoisting means that our variable that was hoisted is now available inside of whatever function or block it is contained in."

You are referring here to Lexical Environments, not hoisting.

Hoisting refers to the fact that variable declarations occur before execution, meaning that variables can appear to be used before they are declared in code order due to being "hoisted" in the global context. (Note: the word hoisting is never referred to in the spec).

Other than that great article :)