자바스크립트에서 호이스팅
목차
Hoisting Function Scope Variable: var
Hoisting Scope Variable: let
Hoisting Constant: const
Hoisting Functions
Hoisting Classes
Conclusion
소개
Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution.
It gives us an advantage that:
- No matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
- It allows us to call functions before even writing them in our code.
Variable Life Cycle: Declaration –> Initialization/Assignment –> Usage
// Variable lifecycle
let a; // Declaration
a = 100; // Assignment
console.log(a); // Usage
JavaScript allows us to both declare and initialize our variables simultaneously, this is the most used pattern:
let a = 100;
Note: Always remember that in the background the JavaScript is first declaring the variable and then initializing them.
in JavaScript, undeclared variables do not exist until the code assigning them is executed. Therefore, assigning a value to an undeclared variable implicitly creates it as a global variable when the assignment is executed. This means that all undeclared variables are global variables.
function codeHoist(){
a = 10;
let b = 50;
}
codeHoist();
console.log(a); // 10
console.log(b); // ReferenceError : b is not defined
Function Life Cycle: Declaration –> Usage
In the case of Function, a function can be declared and later used (or invoked) in the application. The initialization is omitted. For instance:
// Declare
function double(n) {
return n*2;
}
// Use
double(5); // => 10
호이스팅 기능 범위 변수: var
Hoisting with var is somewhat different as when compared to let/const. Let’s make use of var and see how hoisting works:
// var code (global)
console.log(name); // undefined
var name = 'ABIDULLAH786';
console.log(name); // ABIDULLAH786
The above code interpreter sees differently:
//how interpreter sees the above code
var name; // moved to the top
console.log(name); // undefined
name = 'ABIDULLAH786';
console.log(name); // ABIDULLAH786
Hoisting with var work same in function scoped variable as it shows above.
호이스팅 블록 범위 변수: var
Tell now all we discussed is about general hoisting which is 100% applicable on functions and var type variables as defined because let and const types variables cannot access/use able before declaration.
But hoisting work mechanism is different for let types variables.
As if we try to access the let variable before declaring it causes a ReferenceError that the is not defined.
//let example(global)
console.log(name); // ReferenceError: name is not defined
let name='ABIDULLAH786';
console.log(name); // This line will never executes because of reference error
By default a declared yet not initialized variable has an undefined value.
//let example(global)
let name;
console.log(name); // undefined (because the let variable is not initialized)
name='ABIDULLAH786';
console.log(name); // after initialization value is: ABIDULLAH786
호이스팅 상수: const
The constant statement creates and initializes constants inside the block scope:
const COLOR = 'red';
console.log(COLOR); // => 'red'
When a constant is defined, it must be initialized with a value in the same const statement if this rule does not follow the error SyntaxError: Missing initializer in const declaration
will be thrown.
After declaration and initialization, the value of a constant cannot be modified:
const PI = 3.14;
console.log(PI); // => 3.14
PI = 2.14; // TypeError: Assignment to constant variable
The constants cannot be accessed before declaration because of the temporal dead zone. When accessed before declaration, JavaScript throws an error: ReferenceError: is not defined.
console.log(PI); // ReferenceError: PI is not defined
const hoisting has the same behavior as the variables declared with the let statement.
function double(number) {
// temporal dead zone for TWO constant
console.log(TWO); // ReferenceError: Cannot access 'TWO' before initialization
const TWO = 2;
// end of temporal dead zone
return number * TWO;
}
double(5); // => Expected output: 10
호이스팅 기능
Hoisting in a function declaration allows using of the function anywhere in the enclosing scope, even before the declaration.
The following code from the start invokes a function, and defines it:
// Call the hoisted function
equal(1, '1'); // => false
// Function declaration
function equal(value1, value2) {
return value1 === value2;
}
The code works nicely because equal() is created by a function declaration and hoisted to the top of the scope.
Note: Function declaration function declaration function <name>() {...}
and function expression var <name> = function() {...}
both are used to create functions, however have different hoisting mechanisms.
The following sample demonstrates the distinction between both ways:
// Call the hoisted function
sum(4, 7); // => 11
// The variable is hoisted, but is undefined
substract(10, 7); // TypeError: substraction is not a function
// Function declaration
function sum(num1, num2) {
return num1 + num2;
}
// Function expression
var substract = function (num1, num2) {
return num1 - num2;
};
The sum is hoisted entirely and can be called before the declaration.
However subtract is declared using a variable statement and is hoisted too, but has an undefined value when invoked. This scenario throws an error based on the type of variable to which a function is assigned
If the variable is var then the error is: `TypeError: subtraction is not a function.
If the variable is let or const then the error is:
ReferenceError: Cannot access 'subtract' before initialization
호이스팅 클래스
The class variables are registered at the beginning of the block scope. But if you try to access the class before the definition, JavaScript throws ReferenceError: Cannot access '<class_name>' before initialization
.
So the correct approach is to first declare the class and later use it to instantiate objects.
Hoisting in class declarations is similar to variables declared with a let statement
Let's see what happens if a class is instantiated before declaration:
변수 선언문을 사용한 클래스 생성도 마찬가지입니다.
결론
The summary of the post is
Hoisting allow us to use variables, but it depends on the type of variable you are using.
Hoisting allow us to use functions before the declaration, but it depends on in which way you are declaring the function either the simple declaration or with a variable.
Hoisting the var variable allows us to access/use the variable before declaration but the value will be undefined before initialization.
Hoisting the let variable caused a
RefrenceError
if you access/use the let variable before a declaration.The declared but not initialized let variable by default has an undefined value
const hoisting has the same behavior as the variables declared with the let statement.
The const variable must be initialized at the time of declaration.
Classes must be defined before accessing it otherwise the program will through an error
ReferenceError: Cannot access '<class_name>' before initialization
Exploring new concepts in #JavaScript and sharing with others is my passion and it gives me pleasure to help and inspire people. If you have any suggestion or want to add something please comment.
If you liked the post follow me on: , and GitHub !Reference
이 문제에 관하여(자바스크립트에서 호이스팅), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/abidullah786/hoisting-in-javascript-30b1텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)