---
title: "What is hoisting in JavaScript and how does it work?"  
description: "What is hoisting in JavaScript and how does it work?"  
author: "Revati S Misra"  
published: 2023-05-15  
updated: 2023-05-15  
canonical: https://www.mindstick.com/forum/158329/what-is-hoisting-in-javascript-and-how-does-it-work  
category: "javascript"  
tags: ["javascript", "javascript library"]  
reading_time: 2 minutes  

---

# What is hoisting in JavaScript and how does it work?

What is hoisting in [JavaScript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript) and how does it work?

## Replies

### Reply by Aryan Kumar

Hoisting is a JavaScript concept that refers to the process of moving all variable and function declarations to the top of their scope, regardless of where they are actually declared. This means that even if you declare a variable or function in the middle of your code, it will be available as soon as the script starts executing.

For example, the following code will print "Hello World!" even though the greet() function is declared after the console.log() statement:

Code snippet

```plaintext
function greet() {
  console.log("Hello World!");
}

greet();
```

This is because the greet() function is hoisted to the top of its scope, even though it is declared later in the code.

Hoisting can be a bit confusing at first, but it is an important concept to understand if you want to write efficient JavaScript code.

Here are some additional details about hoisting:

- Only variable and function declarations are hoisted. Expressions are not hoisted.
- Hoisting does not move the code itself. It only moves the declaration of the variable or function.
- Hoisting can cause unexpected behavior if you are not careful. For example, if you try to access a variable that has not yet been declared, you will get a ReferenceError.

Here are some tips for avoiding problems with hoisting:

- Always declare your variables and functions at the top of their scope.
- Use let instead of var when declaring variables. let declarations are not hoisted, which can help to prevent errors.
- Use strict mode. Strict mode will prevent some of the problems that can be caused by hoisting.


---

Original Source: https://www.mindstick.com/forum/158329/what-is-hoisting-in-javascript-and-how-does-it-work

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
