본문 바로가기

Programming/JavaScript

Hoisting and The TDZ in Practice

// Variables
console.log(me); // undefined
console.log(job); // Uncaught ReferenceError: Cannot access 'job' before initialization
console.log(year); // Uncaught ReferenceError: Cannot access 'year' before initialization

var me = 'Sunny';
let job = 'technical writer';
const year = 1988;
// Functions
console.log(addDecl(2, 3)); // 5
console.log(addExpr(2, 3)); // Uncaught ReferenceError: Cannot access 'addExpr' before initialization
console.log(addArrow(2, 3)); // Uncaught ReferenceError: Cannot access 'addArrow' before initialization

function addDecl(a, b) {
  return a + b;
}

const addExpr = function (a, b) {
  return a + b;
};

const addArrow = (a, b) => a + b;

What if const를 var로 바꾸면 어떻게 될까?

다른 에러 메시지가 뜬다.

// Functions
console.log(addDecl(2, 3)); // 5
console.log(addExpr(2, 3)); // Uncaught TypeError: addExpr is not a function
console.log(addArrow(2, 3)); //Uncaught TypeError: addArrow is not a function
console.log(addArrow); // undefined

function addDecl(a, b) {
  return a + b;
}

var addExpr = function (a, b) {
  return a + b;
};

var addArrow = (a, b) => a + b;

var로 선언한 변수는 undefined 상태이며,

그럼 undefined에 값을 넣어준거나 마찬가지가 되는거임.

// Example
console.log(numProducts); // undefined
if (!numProducts) deleteShoppingCart();

var numProducts = 10;

function deleteShoppingCart() {
  console.log('All products deleted!'); // All products deleted!
}

undefined는 false value임

근데 ! (not)을 붙였으니 true value가 돼서 deleteShoppingCart()를 실행한거임

 

그래서 결론이 뭐야?

variable declare할 때 var를 쓰지 말아라 🙅‍♀️

default로 const를 쓰고,

정말로 나중에 값을 변경해야 할 여지가 있으면 let을 써라.

 

var x = 1;
let y = 2;
const z = 3;

console.log(x === window.x); // true
console.log(y === window.y); // false
console.log(z === window.z); // false
Variables declared with var will create a property on the global window object.

'Programming > JavaScript' 카테고리의 다른 글

The this Keyword in Practice  (0) 2022.11.21
Variable Environment: Hoisting and The TDZ  (0) 2022.11.20
Scoping in Practice  (1) 2022.11.19
Scope and The Scope Chain  (0) 2022.11.17
SCOPE CHAIN VS. CALL STACK  (0) 2022.11.17