feat(curriculum): Add interactive examples to What Is Hoisting (#63377)

This commit is contained in:
Clarence Bakosi
2025-10-31 20:26:20 +01:00
committed by GitHub
parent 011dcb04b7
commit 409bb41d2c
@@ -5,7 +5,7 @@ challengeType: 19
dashedName: what-is-hoisting
---
# --description--
# --interactive--
Hoisting is a behavior in JavaScript that often confuses beginners, but understanding it can help you avoid subtle bugs in your code. In simple terms hoisting is JavaScript's default behavior of moving declarations to the top of their respective scopes during the compilation phase before the code is executed.
@@ -13,14 +13,20 @@ To understand hoisting, it's important to know that JavaScript runs in two phase
Let's start with variables hoisting, when you declare a variable using the `var` keyword, JavaScript hoists the declaration to the top of its scope. However it's crucial to note that only the declaration is hoisted, not the initialization. This means you can use a variable in your code before you have declared it, but its value will be `undefined` until you actually assign a value to it.
:::interactive_editor
```js
console.log(x); // undefined
var x = 5;
console.log(x); // 5
```
:::
In this code even though we use `x` before declaring it we don't get an error, instead we get `undefined`. This is because JavaScript hoists the declaration `var x` to the top of its scope but not the initialization `x = 5`. It's as if the code were rewritten like this:
:::interactive_editor
```js
var x;
console.log(x); // undefined
@@ -28,8 +34,12 @@ x = 5;
console.log(x); // 5
```
:::
Function hoisting works a bit differently. When you declare a function using the `function` declaration syntax both the function name and the function body are hoisted. This means you can call a function before you've declared it in your code. Here's an example of function hoisting:
:::interactive_editor
```js
sayHello(); // "Hello, World!"
@@ -38,6 +48,8 @@ function sayHello(){
}
```
:::
In this case, we can call `sayHello()` before its declaration because the entire function is hoisted to the top of its scope.
It's important to note that hoisting works differently with `let` and `const` declarations introduced in ES6.