Skip to main content

Command Palette

Search for a command to run...

Javascript Hoisting

Published
•2 min read•View as Markdown
Javascript Hoisting
B

Backend-focused Software Engineer skilled in Node.js, Go, TypeScript, and scalable API design, dedicated to building high-performance, reliable, and efficient web systems.

What is hoisting in JavaScript?

Javascript Hoisting is javascript's default variable which moves all the declarations at the top of the script.

Like, A variable can be used before it has been declared.

Example:

/** 
* For hoisting the variable x is now on the top of the script;
* var x;
**/

x=5; // Initializing the variable x

console.log(x) // 5

var x; // Declaring the variable x

Varibale Declared with let and const:

variable declared with let and const are also hoisted to the top of the script but it will not be initialized;

Meaning: The block of code is aware of the variable, but it cannot be used until it has been declared.

variable with let keyword:

Using a variable with a let keyword before it is declared will result in a ReferenceError.

firstName='Codernex';

console.log(firstName); // ReferenceError

let firstName;

variable with the const keyword

Using a const variable before it is declared, is a syntax error, so the code will simply not run.

// This code will not run.
carName = "Volvo";
const carName;

Remember Javascript hoisting only works with the declaration, not with the initialization;

/**
* Javascript hoisting only move the variable declaration to the 
* top of the script, not the initialization that's why it will 
* print undefined
* It will look like - var x; but it will not be initialized with the value 5;
*/
console.log(x) // undefined
var x=5; // Declaring & Initializing with 5;

Declare Your Variables At the Top!

Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript.

If a developer doesn't understand hoisting, programs may contain bugs (errors).

More from this blog

Codernex: Exploring Tech & Programming

9 posts

A platform where I share insights, tutorials, and expertise across a range of technologies, helping others stay informed and grow their skills.