[JavaScript] - Hoisting๐Ÿ—

Jane Shinยท2021๋…„ 4์›” 4์ผ
1

JavaScript

๋ชฉ๋ก ๋ณด๊ธฐ
6/8

Hoisting์ด๋ž€, ์„ ์–ธ๋“ค์„ ๋ชจ๋‘ ๋Œ์–ด์˜ฌ๋ ค์„œ ์Šค์ฝ”ํ”„์˜ ์ตœ์ƒ๋‹จ์— ์„ ์–ธํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope (to the top of the current script or the current function)

'let, const' vs. 'var'

let๊ณผ const๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด, ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•˜๊ธฐ ์ „์— ์‚ฌ์šฉํ•˜๋ ค ํ•  ๋•Œ ์—๋Ÿฌ๊ฐ€ ์ผ์–ด๋‚œ๋‹ค.

carName = "Volvo";
let carName; //ReferenceError

carName = "Volvo";
const carName; //ReferenceError

x;  //ReferenceError
let x = 3;

๋ฐ˜๋ฉด, var๋กœ ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•˜๋ฉด ์„ ์–ธํ•˜๊ธฐ ์ „์—๋„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

carName = "Volvo";
var carName; //Volvo

x; //undefined
var x = 3;
x; //3

์™œ ์ด๋Ÿด๊นŒ? var๋กœ ์„ ์–ธํ•œ ๋ณ€์ˆ˜๋Š” ๋Œ์–ด์˜ฌ๋ฆฐ๋‹ค๋Š” ๋œป์˜ hoisting ๋ฉ”์ปค๋‹ˆ์ฆ˜์„ ๋”ฐ๋ฅด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋Š” ํ•จ์ˆ˜๋‚˜ ์ „์—ญ ์Šค์ฝ”ํ”„ ์ „์ฒด๋ฅผ ์‚ดํŽด๋ณด๊ณ , var๋กœ ์„ ์–ธํ•œ ๋ณ€์ˆ˜๋ฅผ ๋งจ ์œ„๋กœ ๋Œ์–ด์˜ฌ๋ฆฐ๋‹ค. ํ•˜์ง€๋งŒ ์„ ์–ธ๋งŒ ๋Œ์–ด์˜ฌ๋ ค์ง€๊ณ , ํ• ๋‹น์€ ๋Œ์–ด์˜ฌ๋ ค์ง€์ง€ ์•Š๋Š”๋‹ค.

var์˜ ์ด๋Ÿฌํ•œ ํŠน์„ฑ ๋•Œ๋ฌธ์— ํ˜ผ๋ž€์Šค๋Ÿฌ์šด ์ฝ”๋“œ๊ฐ€ ์ƒ๊ธธ ์ˆ˜ ์žˆ๋‹ค. ๊ทธ๋ž˜์„œ ES6์—์„œ let์ด ๋“ฑ์žฅํ–ˆ๋‹ค. ์•„์ง์€ ES5๊ฐ€ ์™„์ „ํžˆ ES6๋กœ ๋Œ€์ฒด๋œ ๊ฑด ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— var์„ ์•Œ๊ธฐ๋Š” ํ•ด์•ผ ํ•˜์ง€๋งŒ ๋‚˜์ค‘์—๋Š” ์™„์ „ํžˆ ์—†์–ด์งˆ ์ˆ˜๋„ ์žˆ๋‹ค.

ํ•จ์ˆ˜ ํ‘œํ˜„์‹(Function expressions) vs. ํ•จ์ˆ˜ ์„ ์–ธ๋ฌธ(Function declarations)

1. Function expressions are NOT hoisted.

  • ํ•จ์ˆ˜ ํ‘œํ˜„์‹์€ ํ˜ธ์ด์ŠคํŒ…๋˜์ง€ ์•Š๋Š”๋‹ค.
expression(); //Output: "TypeError: expression is not a function

var expression = function(){
	console.log('Will this work?');
}

2. Function declarations are hoisted.

  • ํ•จ์ˆ˜์„ ์–ธ๋ฌธ์€ ์ฝ”๋“œ๋ฅผ ๊ตฌํ˜„ํ•œ ์œ„์น˜์™€ ๊ด€๊ณ„ ์—†์ด, ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ ํŠน์ง•์ธ ํ˜ธ์ด์ŠคํŒ…์— ๋”ฐ๋ผ ๋ธŒ๋ผ์šฐ์ €๊ฐ€ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ๋ฅผ ํ•ด์„ํ•  ๋•Œ ๋งจ ์œ„๋กœ ๋Œ์–ด ์˜ฌ๋ ค์ง„๋‹ค.
hoisted(); //This function has been hoisted.

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

ํ˜ธ์ด์ŠคํŒ… ์šฐ์„ ์ˆœ์œ„(Order of precedence)

  1. Variable assignment takes precedence over function declaration
  2. Function declarations take precedence over variable declarations

ํ•จ์ˆ˜ ์„ ์–ธ์€ ๋ณ€์ˆ˜ ์„ ์–ธ๋ณด๋‹ค ์ƒ์œ„์— ์žˆ์ง€๋งŒ, ๋ณ€์ˆ˜ ํ• ๋‹น๋ณด๋‹ค๋Š” ํ•˜์œ„์— ์žˆ๋‹ค.

Function declarations are hoisted over variable declarations but not over variable assignments.

1. Variable assignment over function declaration

var double = 22;

function double(num) {
	return (num*2);
}

console.log(typeof double); // Output: number

2. Function declarations over variable declarations

var double;

function double(num) {
	return (num*2);
}

console.log(typeof double); // Output: function

JavaScript Hoisting

[JavaScript] ํ˜ธ์ด์ŠคํŒ…(Hoisting)์ด๋ž€ - Heee's Development Blog

Understanding Hoisting in JavaScript | DigitalOcean

0๊ฐœ์˜ ๋Œ“๊ธ€