var, let, const

ggomadevยท2022๋…„ 3์›” 22์ผ
0

Today I Learned

๋ชฉ๋ก ๋ณด๊ธฐ
13/15
post-thumbnail
post-custom-banner

1. ๋ณ€์ˆ˜์˜ ์ƒ์„ฑ๊ณผ์ •

๐Ÿ“Œ ์ดˆ๊ธฐํ™”: undefined๋ฅผ ํ• ๋‹นํ•ด์ฃผ๋Š” ๋‹จ๊ณ„
๐Ÿ“Œ ๋ณ€์ˆ˜: ๊ฐ’์„ ๋‹ด๊ธฐ ์œ„ํ•œ ๊ณต๊ฐ„

const

  1. ์„ ์–ธ ๋ฐ ์ดˆ๊ธฐํ™” ๋ฐ ํ• ๋‹น ๋‹จ๊ณ„

var

  1. ์„ ์–ธ ๋ฐ ์ดˆ๊ธฐํ™” ๋‹จ๊ณ„
  2. ํ• ๋‹น ๋‹จ๊ณ„

let

  1. ์„ ์–ธ ๋‹จ๊ณ„
  2. ์ดˆ๊ธฐํ™” ๋‹จ๊ณ„
  3. ํ• ๋‹น ๋‹จ๊ณ„

2. ๋ณ€์ˆ˜ ํŠน์ง•๊ณผ ํ˜ธ์ด์ŠคํŒ…

const

๐Ÿ“Œconst๋กœ ์„ ์–ธํ•œ ๋ณ€์ˆ˜์—๋Š” ์ƒˆ๋กœ์šด ๊ฐ’์„ ํ• ๋‹นํ•  ์ˆ˜ ์—†๋‹ค.


var

๐Ÿ“Œ์„ ์–ธํ•˜๊ธฐ ์ „์— ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

console.log(b) // undefined
var b = 'bee'

var์—์„œ ์œ„์˜ ์ฝ”๋“œ๋Š” ์•„๋ž˜์™€ ๊ฐ™์ด ๋™์ž‘์ด ์ด๋ฃจ์–ด์ง„๋‹ค. (3)์ด (1)๋กœ ์‹ค์ œ ์˜ฌ๋ผ๊ฐ€๋Š” ๊ฒƒ์€ ์•„๋‹ˆ์ง€๋งŒ ๊ทธ์™€ ๊ฐ™์ด ๋Œ์–ด์˜ฌ๋ ค์ง„ ๊ฒƒ ์ฒ˜๋Ÿผ ๋™์ž‘ํ•œ๋‹ค. (ํ˜ธ์ด์ŠคํŒ…)

var bug; // (1)
console.log(bug) // undefined (2)
bug = 'bee'//(3)

์ฝ˜์†”์— ์ฐ์—ˆ์„ ๋•Œ 'undefined'๊ฐ€ ๋˜๋Š” ์ด์œ ๋Š” ์„ ์–ธ์€ ํ˜ธ์ด์ŠคํŒ…๋˜์ง€๋งŒ ํ• ๋‹น์€ ํ˜ธ์ด์ŠคํŒ…๋˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.


๐Ÿ“Œ ํ•œ ๋ฒˆ ์„ ์–ธ๋œ ๋ณ€์ˆ˜๋ฅผ ๋‹ค์‹œ ์„ ์–ธํ•  ์ˆ˜ ์žˆ๋‹ค.

var name = 'Mary'
console.log(name) // Mary

var name = 'William'
console.log(name) // William

3. let

๐Ÿ“Œ ์„ ์–ธ ์ „์— ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค.

console.log(bug) // ERROR!!
// Uncaught ReferenceError: bug is not defined
let bug = 'bee'

TDZ(Temporal Dead Zone): ์ผ์‹œ์  ์‚ฌ๊ฐ์ง€๋Œ€. TDZ ์•ˆ์— ์žˆ๋Š” ๋ณ€์ˆ˜๋“ค์€ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค. let๊ณผ const๋Š” TDZ์˜ ์˜ํ–ฅ์„ ๋ฐ›๊ธฐ์— ํ• ๋‹น ์ „์— ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค.

์˜ˆ์‹œ1

console.log(bug) // TEMPORAL DEAD ZONE!!! ์‚ฌ์šฉ๋ถˆ๊ฐ€
let bug = 'bee'// ํ•จ์ˆ˜์˜ ์„ ์–ธ, ํ• ๋‹น
console.log(bug) // ์‚ฌ์šฉ๊ฐ€๋Šฅ

์˜ˆ์‹œ2

let dessert = 'cheeseCake';
function displayDessert() {
	console.log(dessert) //  TEMPORAL DEAD ZONE
	
  	let dessert = 'chocolateCake'
} 

displayDessert() // ERROR!!
// Cannot access 'dessert' before initialization

๐Ÿ“Œ ์ด๋ฏธ ํ•œ ๋ฒˆ ์„ ์–ธ๋œ ๋ณ€์ˆ˜๋ฅผ ๋‹ค์‹œ ์„ ์–ธํ•  ์ˆ˜ ์—†๋‹ค.

let name = 'Mary'
console.log(name) // Mary

let name = 'William' // ERROR!!
// Uncaught SyntaxError: Identifier name has already been declared.
console.log(name) 
profile
๐Ÿ’ป
post-custom-banner

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