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; x = 1; console.log(x + " " + y); y = 2; | cs |
References :
'0 > javascript' 카테고리의 다른 글
JavaScript 표준의 선구자들 : CommonJS와 AMD (0) | 2019.04.26 |
---|---|
외부 API를 사용해서 데이터를 끌어오는 방법 (AJAX, Fetch API & Async/Await) (0) | 2019.04.02 |
What is a Closure? (0) | 2019.03.07 |
What is a Promise? (0) | 2019.02.27 |
Node.js (0) | 2018.11.30 |