The Difference Between Function and Block Scope in JavaScript - Lee-hyuna/33-js-concepts-kr GitHub Wiki

์ตœ๊ทผ ์–ด๋–ค ์‚ฌ๋žŒ์ด Javscript ์˜ ๊ธฐ๋ณธ ๊ณผ์ •์œผ๋กœ ๋Œ์•„๊ฐ€๊ณ  ์‹ถ๋‹ค๊ณ  ํ–ˆ์„ ๋•Œ, Wes Bos ์˜ "ES6 for Everyon" ๊ณผ์ •์„ ์ถ”์ฒœํ–ˆ๋‹ค. Wes ๋Š” ๋›ฐ์–ด๋‚œ ์„ ์ƒ๋‹˜์ด๋ฉฐ ๋ณต์žกํ•œ ์ฃผ์ œ์— ๋Œ€ํ•ด์„œ ์ž˜ ํ’€์–ด ์„ค๋ช… ํ•  ์ˆ˜ ์žˆ๋Š” ์ปค๋ฎค๋‹ˆ์ผ€์ดํ„ฐ์ด๋‹ค.

Wes ์˜ ๊ณผ์ •์„ ํ†ตํ•˜์—ฌ ๊ธฐ์ดˆ๋ฅผ ๋‹ค์กŒ๊ณ , Javascript ๋ฅผ ํƒํ—˜ํ•˜๊ธฐ ์‹œ์ž‘ํ–ˆ๋‹ค.

var, let ๊ณผ const ์˜ ์ฐจ์ด์ 

JS ์—์„œ ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•˜๋Š” ์„ธ๊ฐ€์ง€ ๋ฐฉ๋ฒ•:

var width = 100;
let height = 200;
const key = 'abc123';

var

var ๋Š” ์žฌํ• ๋‹น๋˜๊ณ  ์—…๋ฐ์ดํŠธ ๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

// Define the variable:
var width = 100;

// Call the variable:
width;
// It returns:
100
// Reassign the variable and call it again:
width = 200;

width;
// Returns:
200

var ๋ณ€์ˆ˜๋Š” ํ•จ์ˆ˜ ์Šค์ฝ”ํ”„์ž…๋‹ˆ๋‹ค. ์ด๊ฒƒ์€ ๋ฌด์—‡์„ ์˜๋ฏธํ•˜๋‚˜? ์ƒ์„ฑ๋œ ํ•จ์ˆ˜ ๋‚ด์—์„œ๋งŒ ์‚ฌ์šฉ ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•œ๋‹ค. ํ•จ์ˆ˜ ๋‚ด๋ถ€์—์„œ ์ƒ์„ฑ๋˜์ง€ ์•Š์•˜๋‹ค๋ฉด ์ „์—ญ ๋ฒ”์œ„๋กœ ์ง€์ •๋œ๋‹ค.

ํ•จ์ˆ˜ ๋‚ด๋ถ€์— var ๊ฐ€ ์ •์˜๋˜์–ด ์žˆ๊ณ  ํ•จ์ˆ˜ ์™ธ๋ถ€์—์„œ ํ˜ธ์ถœํ•˜๋ ค๊ณ ํ•˜๋ฉด ๋™์ž‘ํ•˜์ง€ ์•Š๋Š”๋‹ค.

function setWidth(){
    var width = 100;
    console.log(width);
}
width;
// Returns:
Uncaught ReferenceError: width is not defined

var ๋Š” ํ•จ์ˆ˜ ๋‚ด์—์„œ ์ •์˜ ๋˜๊ธฐ ๋–„๋ฌธ์— ํ•จ์ˆ˜์˜ ๋ฐ–์—์„œ๋Š” ์‚ฌ์šฉ์ด ๋ถˆ๊ฐ€๋Šฅ ํ•œ ๊ฒƒ ์ด๋‹ค.

์Šค์ฝ”ํ”„๋ฅผ ์ดํ•ดํ•˜๋‹ค

Example: 
var age = 100;
  if (age > 12){
    var dogYears = age * 7;
    console.log(`You are ${dogYears} dog years old!`);
  }

์œ„์˜ ์˜ˆ์ œ์—์„œ console ์˜ ์ถœ๋ ฅ๊ฒฐ๊ณผ

100
You are 700 dog years old!

๋งŒ์•ฝ dogYears ๋ฅผ ๋ถ€๋ฅธ๋‹ค๋ฉด

dogYears;
// returns:
700

var ๋ณ€์ˆ˜๋Š” ํ•จ์ˆ˜ ์Šค์ฝ”ํ”„์˜ ๋ฒ”์œ„์ด๋ฏ€๋กœ var dogYears ์œ„ ์˜ˆ์ œ์˜ ํ•จ์ˆ˜ ์•ˆ์—์„œ ์ •์˜ ๋˜์–ด ์žˆ์ง€ ์•Š์•˜๊ธฐ ๋•Œ๋ฌธ์— - var๊ฐ€ 'window'๋˜๋Š” ์ „์—ญ ๋ฒ”์œ„์—์„œ ๋Œ€์‹  ์ •์˜๋œ๋‹ค

์ฆ‰, var๋Š” ์ค‘๊ด„ํ˜ธ์— ๊ตญํ•œ๋˜์ง€ ์•Š๋Š”๋‹ค

let, const ์˜ ์ด์ 

let ๊ณผ const ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์–ด๋–ค ์ด์ ์ด ์žˆ์„๊นŒ ? ์Šค์ฝ”ํ”„๊ฐ€ ํ•จ์ˆ˜ ๋‹จ์œ„๊ฐ€ ์•„๋‹ˆ๋ผ ๋ธ”๋ก ๋‹จ์œ„๋กœ ๋ฐ”๋€Œ๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

๋ธ”๋ก์ด๋ž€ ๋ฌด์—‡์ผ๊นŒ ? {} ์ค‘๊ด„ํ˜ธ๋ฅผ ๋ธ”๋Ÿญ์ด๋ผ๊ณ ํ•œ๋‹ค.

์œ„์˜ ์˜ˆ์ œ์—์„œ var ๋ฅผ const ๋กœ ๋ณ€๊ฒฝํ•œ ํ›„ dogYears ๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด Uncaught ReferenceError ์—๋Ÿฌ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

var age = 100;
  if (age > 12){
    let dogYears = age * 7;
    console.log(`You are ${dogYears} dog years old!`);
  }

let ๋Œ€์‹  const ๋ฅผ ์ด์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  • var ๋Š” ํ•จ์ˆ˜ ์Šค์ฝ”ํ”„์ด๋‹ค
  • let, const ๋Š” ๋ธ”๋ก ์Šค์ฝ”ํ”„์ด๋‹ค
  • ํ•จ์ˆ˜ ์Šค์ฝ”ํ”„๋Š” ํ•จ์ˆ˜ ์•ˆ์ด๋‹ค
  • ๋ธ”๋ก ์Šค์ฝ”ํ”„๋Š” ์ค‘๊ด„ํ˜ธ์ด๋‹ค