Frontend Development: JavaScript Hoisting

Peter Jeon·2023년 6월 20일
0

Frontend Development

목록 보기
21/80
post-custom-banner

JavaScript Hoisting

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope, before the code has been executed.

Understanding Variable Hoisting

Variable Hoisting

In JavaScript, both var and function declarations are hoisted. However, the initializations are not.

console.log(myVar); // undefined
var myVar = 5;
console.log(myVar); // 5

In this example, the variable myVar is hoisted, but its initialization with the value 5 is not. Therefore, the first console.log prints undefined.

Function Hoisting

Function declarations are hoisted, with both their name and body.

hoistedFunction();  // Output: This function has been hoisted.

function hoistedFunction() {
  console.log('This function has been hoisted.');
}

Here, the entire function hoistedFunction is hoisted, so calling the function before its declaration in the code does not cause an error.

let and const Hoisting

ES6 introduced two new types of variable declarations: let and const. They are also hoisted, but accessing them before the declaration leads to a Reference Error.

console.log(myLetVar); // ReferenceError
let myLetVar = 5;

Hoisting can cause unexpected results, so it's generally a good idea to always declare your variables at the top of their scope.

profile
As a growing developer, I am continually expanding my skillset and knowledge, embracing new challenges and technologies
post-custom-banner

0개의 댓글