본문 바로가기

0/javascript

What is a Hoisting?

반응형

Conceptually, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens.

Instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code.



Example


Technical example

One of the advantage of JavaScript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code.


1
2
3
4
5
6
7
8
9
10
11
/*
    Even though we call the function in our code first,
    before the funciton is written, the code still works.
    This is because of how context execution works in JavaScript.
*/
 
showName("Kim");
 
function showName(name){
    console.log("My name is " + name);
}
cs


Hoisting works well with other data types and variables. The variables can be initialized and used before they are declared.


Only declarations are hoisted

JavaScript only hoists declarations, not initializations. If a variable is declared and initialized after using it, the value will be undefined.


1
2
3
4
console.log(num) // undefined
 
var num;
num = 6;
cs


The below two examples demonstrate the same behavior.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
var x = 1;
console.log(x + " " + y); // 1 undefined
var y = 2;
 
/////////////////////////////////
 
// Hoisting only declarations 
var x;
var y;
 
= 1;
console.log(x + " " + y);
= 2;
 
cs


References :

https://developer.mozilla.org/en-US/docs/Glossary/Hoisting

반응형