Skip to content

What Is Hoisting in JavaScript?

"Hoisting" is a JavaScript concept, so it is not tied to Vue itself. Vue is a JavaScript framework built on top of the language, and hoisting comes from how JavaScript runs code.

Before JavaScript executes code, variable and function declarations are moved ("hoisted") to the top of their scope. This means a variable or function can be referenced before the line that declares it.

For example:

JavaScript
console.log(x); // undefined
var x = 5;
console.log(x); // 5

When console.log(x); runs before var x = 5;, the result is undefined: the declaration of x (var x) has been hoisted, but its value (5) has not been assigned yet.

Vue does not add anything special around hoisting, but it is built on JavaScript and works with its general concepts, so understanding hoisting helps when writing Vue code.

Note: Only variables declared with var are hoisted with the value undefined. let and const are hoisted too, but cannot be accessed before the line that declares them (the Temporal Dead Zone); in that case console.log(x) throws a ReferenceError.

Have a question about this article? Write to me