Hoisting Variables With var, let, and const
The behavior of variables, when hoisted, depends on the keyword you declare them with, as each keyword behaves differently.
Accessing an uninitialized variable declared with the var keyword will return undefined. For example:
var foo = 2;
The above code logs undefined because it calls console.log before it initializes the variable.
foo = 2;
var foo = 10;
Trying to access a variable outside its scope will result in a ReferenceError.
let and const
var foo = 5;
let bar = 10;
const baz = 15;
You cannot access variables declared with the let and const keywords before initializing them with a value.
A function declaration is a function declared with a name, while a function expression is a function whose name you can omit. For example:
const bar = () =>
var bar = function expression()
This code calls foo before declaring and initializing it as a function, but it still logs 5 to the console. However, trying to call bar results in a TypeError.
Being aware of hoisting and the potential errors that could occur if managed wrongly can save you long hours of debugging. Here are some ways you can manage hoisting.
Declare Variables Inside Functions
Declare variables inside the functions that will access them. You won’t always be able to do this, as you may need a global variable that you can access within multiple functions. So ensure that you only declare variables globally if you really need to.
Declare Variables With let or const
Declare Variables at the Top of Their Scope
Using Strict Mode
For example, in “sloppy mode,” due to hoisting, you can access a variable outside of the initialized function, even though it wasn’t declared:
foo = 20;
You can use strict mode to fix this behavior and throw an error if you try accessing the variable outside its function scope.
Strict mode does not stop hoisting altogether. Instead, it prevents the most confusing and error-prone forms of hoisting. It’s still important to understand the general concept and the rules behind hoisting, even when using the strict mode safety net.
To opt into strict mode at a global level, declare the syntax at the top of your script file:
"use strict"; // or 'use strict'
To opt into strict mode at a function level, declare the syntax at the top of a function body before any statements:
If you declare strict mode at a function level, the setting will apply only to statements inside that function.
Declaring strict mode at a global level prevents variables from being accessed outside their respective scopes:
foo = 20;
Understand What Affects Hoisting
Several factors can affect hoisting, so it is best to avoid any occurrence of variable or function hoisting in your code.