[HTML/CSS/JS] var, let, const

var, let, const

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•  ๋•Œ ์‚ฌ์šฉํ•˜๋Š” var, let, const์˜ ์ฐจ์ด๋ฅผ ์•Œ์•„๋ณด์ž.

var

var๋Š” const์™€ ๋‹ค๋ฅด๊ฒŒ ๊ฐ’์ด ๋ณ€ํ•  ์ˆ˜ ์žˆ๋Š” ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•  ๋•Œ ์‚ฌ์šฉ๋œ๋‹ค.
const์™€์˜ ์ฐจ์ด๋Š” ๋ณ€์ˆ˜์ด๋ƒ ์ƒ์ˆ˜์ด๋ƒ์ธ๋ฐ let ๊ณผ์˜ ์ฐจ์ด๋Š” ๋ฌด์—‡์ผ๊นŒ?
var๋Š” function scope์ด๊ณ , let๊ณผ const๋Š” block scope์ด๋‹ค.

  if(true){
      var num = 100;
  }
  console.log(num); // 100 ์ถœ๋ ฅ
  num += 200;
  console.log(num); // 300 ์ถœ๋ ฅ

์œ„์˜ ์˜ˆ์ œ๋ฅผ ํ™•์ธํ•ด๋ณด์ž.
๋ธ”๋ก ์•ˆ์— num์ด ์„ ์–ธ๋˜๊ณ  ๋ธ”๋ก์ด ๋๋‚ฌ๊ธฐ ๋•Œ๋ฌธ์— num์ด ์†Œ๋ฉธ๋  ๊ฒƒ ๊ฐ™์ง€๋งŒ var๋Š” function scope์ด๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค.

  function testFunc(){
      var num = 100;
      console.log("testFunction");
      return;
  }
  testFunc();
  console.log(num);

์œ„์˜ ์˜ˆ์ œ๊ฐ€ function scope๋ฅผ ๋ฒ—์–ด๋‚˜์„œ num์„ ํ˜ธ์ถœํ•˜๋ฏ€๋กœ num is not defined ๋ฉ”์‹œ์ง€๊ฐ€ ๋‚˜์˜จ๋‹ค.

let

  if(true){
      let num = 100;
  }
  console.log(num); // ์˜ค๋ฅ˜

let์€ block scope์ด๋ฏ€๋กœ ๋ธ”๋ก์„ ๋ฒ—์–ด๋‚˜๋ฉด ์ถœ๋ ฅ๋˜์ง€ ์•Š๊ณ  ์˜ค๋ฅ˜๊ฐ€ ๋‚œ๋‹ค.

  let num = 100;
  console.log(num); // 100 ์ถœ๋ ฅ
  num = 200;
  console.log(num); // 200 ์ถœ๋ ฅ

๋ธ”๋ก ๋ฒ”์œ„์—๋งŒ ์žˆ๋‹ค๋ฉด let์€ ๋ณ€์ˆ˜ ์„ ์–ธ์— ์‚ฌ์šฉ๋˜๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ’์ด ์–ผ๋งˆ๋“  ๋ฐ”๋€” ์ˆ˜ ์žˆ๋‹ค.
var๋Š” block์„ ๋ฒ—์–ด๋‚˜๋„ ์‚ฌ์šฉ๋˜๋ฏ€๋กœ ์—ฌ๋Ÿฌ ํ˜ผ๋ž€์„ ์ค„ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ง€์–‘ํ•˜๊ณ  let์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค.

const

const ๋˜ํ•œ block scope์ด๋ฏ€๋กœ block์ด ๋๋‚˜๋ฉด ์†Œ๋ฉธ๋œ๋‹ค.

  if(true){
      const num = 100;
  }
  console.log(num); // ์˜ค๋ฅ˜

๋˜ const๋Š” ์ƒ์ˆ˜๋ฅผ ์„ ์–ธํ•  ๋•Œ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ, ๊ฐ’์„ ๋ณ€๊ฒฝํ•˜๋ฉด ์˜ค๋ฅ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

  const num = 100;
  console.log(num); // 100 ์ถœ๋ ฅ
  num = 200;
  console.log(num); // ์˜ค๋ฅ˜

TypeError: Assignment to constant variable. ์˜ค๋ฅ˜๊ฐ€ ์ถœ๋ ฅ๋œ๋‹ค.