EXECUTION CONTEXT
- Variable environment
- Scope chain
- this keyword
Hoisting: Makes some types of variables accessible/usable in the code before they are actually declared.
Variables lifted to the top of their scope.
Behind the scenes
Before execution, code is scanned for variable declarations, and for each variable, a new property is created in the variable environment object.
HOISTED | INITIAL VALUE | SCOPE | |
function declarations | YES | Actual function | Block |
var variables | YES | undefined | Function |
let and const variables | NO | <uninitialized>, TDZ | Block |
function expressions and arrows | Depends if using var or let/const |
function declarations
- Function은 hoisting 덕분에 declare되기 전에 사용할 수 있음
- block scope is valid only in strict mode. Otherwise: function scope!
var variables
- Function과 달리 아직 declare되지 않은 var variable을 access하려고 하면 we don't get the declared value
but we get 'undefined'
- error가 뜨는 것도 아니고 or the actual value를 얻는 것도 아님
-> modern javascript에서 var를 거의 사용하지 않는 이유기도 함
let and const variables
- HOISTED: technically yes. But not in practice
- TDZ: Temporal Dead Zone
- declare 되기 전인 let이나 const variable 사용하려고 하면 error 뜸
function expressions and arrows
- Function expressions or arrow function declared with var -> hoisted undefined
But if created with let or const -> it's not usable before it's declared in the code because of TDZ
TEMPORAL DEAD ZONE, LET AND CONST
const myName = 'Sunny';
if (myName === 'Sunny') {
// TEMPORAL DEAD ZONE FOR job VARIABLE ---
console.log(`Sunny is a ${job}`); // Uncaught ReferenceError: Cannot access 'job' before initialization
const age = 2022 - 1988;
console.log(age);
// --- TEMPORAL DEAD ZONE FOR job VARIABLE
const job = 'technical writer';
console.log(x); // Uncaught ReferenceError: x is not defined
}
같은 ReferenceError지만 다른 종류의 error message가 뜨는 거 알 수 있음
WHY TDZ?
- Makes it easier to avoid and catch errors: accessing variables before declaration is bad practice and should be avoided;
- Makes const variables actually work
WHY HOISTING?
- Using functions before actual declaration;
- var hoisting is just a byproduct.
'Programming > JavaScript' 카테고리의 다른 글
The this Keyword (0) | 2022.11.21 |
---|---|
The this Keyword in Practice (0) | 2022.11.21 |
Hoisting and The TDZ in Practice (0) | 2022.11.20 |
Scoping in Practice (1) | 2022.11.19 |
Scope and The Scope Chain (0) | 2022.11.17 |