๐ŸŸจ JavaScript/๊ฐœ๋…

[๋“œ๋ฆผ์ฝ”๋”ฉ/์ฝ”๋”ฉ์•™๋งˆ] scope์™€ hoisting, ๊ทธ๋ฆฌ๊ณ  TDZ (์ถ”๊ฐ€)

Zoeeey 2022. 4. 14. 13:12

scope

๋ณ€์ˆ˜์˜ '์ˆ˜๋ช…'

  1. local scope
  2. global scope

1. local scope

์ง€์—ญ๋ณ€์ˆ˜(Local Variable)๊ฐ€ ๊ฐ€์ง€๋Š” ๋ฒ”์œ„๋กœ, ํ•จ์ˆ˜๊ฐ€ ์‹คํ–‰๋˜๋ฉด ๋งŒ๋“ค์–ด์ง€๊ณ  ํ•จ์ˆ˜๊ฐ€ ์ข…๋ฃŒ๋˜๋ฉด ์†Œ๋ฉธํ•œ๋‹ค. ํ•จ์ˆ˜ ์™ธ๋ถ€์—์„œ๋Š” ์ ‘๊ทผํ•  ์ˆ˜ ์—†๋‹ค.

2. global scope

์ „์—ญ๋ณ€์ˆ˜(Global Variable)๊ฐ€ ๊ฐ€์ง€๋Š” ๋ฒ”์œ„๋กœ ๋ณ€์ˆ˜๊ฐ€ ํ•จ์ˆ˜ ์™ธ๋ถ€์—์„œ ์„ ์–ธ๋˜์–ด ํ”„๋กœ๊ทธ๋žจ ์ „์ฒด์—์„œ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค.


 

let globalMsg = 'global'; // global variable
function printMsg() {
    let msg = 'hello';
    console.log(msg); // local variable
    console.log(globalMsg); // ์ •์ƒ์ž‘๋™ํ•œ๋‹ค.
}
printMsg();
console.log(msg); //RefenceError๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

์•ˆ(local scope ๋‚ด๋ถ€)์—์„œ๋Š” ๋ฐ–(global scope)๋ฅผ ๋ณผ ์ˆ˜ ์žˆ์ง€๋งŒ, ๋ฐ–์—์„œ๋Š” ์•ˆ์„ ๋ณผ ์ˆ˜ ์—†๋‹ค.


hoisting

scope ๋‚ด๋ถ€ ์–ด๋””์„œ๋“  ๋ณ€์ˆ˜๊ฐ€ ์ตœ์ƒ์œผ๋กœ ๋Œ์–ด์˜ฌ๋ ค์ง„ ๊ฒƒ์ฒ˜๋Ÿผ ๋™์ž‘ํ•œ๋‹ค.

  • 'var๋กœ ์„ ์–ธํ•œ ๋ชจ๋“  ๋ณ€์ˆ˜'์™€ 'ํ•จ์ˆ˜ ์„ ์–ธ๋ฌธ'์€ hoisting๋œ๋‹ค.
  • '๋ณ€์ˆ˜ ์„ ์–ธ'์ด 'ํ•จ์ˆ˜ ์„ ์–ธ'๋ณด๋‹ค, 'ํ• ๋‹น๋˜์–ด์žˆ๋Š” ๋ณ€์ˆ˜'๊ฐ€ 'ํ• ๋‹น๋˜์–ด์žˆ์ง€ ์•Š์€ ๋ณ€์ˆ˜'๋ณด๋‹ค ๋จผ์ € ์ธ์‹๋œ๋‹ค.

TDZ (Temporal Dead Zone)

๋ณ€์ˆ˜๊ฐ€ ์„ ์–ธ๋˜์—ˆ์ง€๋งŒ ์ดˆ๊ธฐํ™”๋˜๊ธฐ ์ „๊นŒ์ง€ ์•ก์„ธ์Šคํ•  ์ˆ˜ ์—†๋Š” ์˜์—ญ(๋ณ€์ˆ˜ ํ• ๋‹น ์ „์œผ๋กœ ์‚ฌ์šฉ์ด ๋ถˆ๊ฐ€ํ•œ ์˜์—ญ)์ด๋‹ค. let ๋ฐ const ํ‚ค์›Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•  ๋•Œ ๋ฐœ์ƒํ•œ๋‹ค.

console.log(myVar); // ์—๋Ÿฌ! myVar๋Š” TDZ์— ์žˆ์œผ๋ฏ€๋กœ ์ฐธ์กฐํ•  ์ˆ˜ ์—†์Œ

let myVar = 42; // ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•˜๊ณ  ์ดˆ๊ธฐํ™”
console.log(myVar); // ์ด์ œ myVar์˜ ๊ฐ’์ธ 42๋ฅผ ์ถœ๋ ฅ
if (true) {
  console.log(myVar); // ์—๋Ÿฌ! myVar๋Š” TDZ์— ์žˆ์œผ๋ฏ€๋กœ ์ฐธ์กฐํ•  ์ˆ˜ ์—†์Œ
  let myVar = 42; // ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•˜๊ณ  ์ดˆ๊ธฐํ™”
  console.log(myVar); // ์ด์ œ myVar์˜ ๊ฐ’์ธ 42๋ฅผ ์ถœ๋ ฅ
}

์ถœ์ฒ˜ : ๋“œ๋ฆผ์ฝ”๋”ฉ https://www.youtube.com/@dream-coding / ์ฝ”๋”ฉ์•™๋งˆ https://www.youtube.com/@codingangma