Hoisting

Introduction

  • var variable and normal function will be firstly created with undefined and real function during the creation phase of execution context, that' why, we can see it undefined during execution phase

  • Below is the an example

Normal Function / var

var x = 1; // 初始化 x
console.log(x + " " + y);  // '1 undefined'
var y = 2;
//上下的程式結果都一樣

var x = 1; // 初始化 x
var y; // 宣告 y
console.log(x + " " + y);  // '1 undefined'
y = 2; // 初始化 y


test();
function test() {
    console.log("test");
}
// Output: test

Arrow Function / let and const

// Arrow function and let / const are applicable to hoisting
test();
const test = () => {
    console.log("test");
}

// Reference Error

console.log(x);
let  x = 1;
// x is not defined

Last updated

Was this helpful?