var, const, let - 2

남성윤·2022년 12월 28일
0

학습 일지

목록 보기
5/369

2. let, const

0. 공통점

1. 호이스팅 단계

let const는 선언 단계와 초기화 단계가 별개로 이루어진다.
호이스팅이 이루어지며 선언은 실행되지만, 초기화는 런타임에 이루어지기 때문에, var과는 달리 먼저 참조가 불가능하다.

console.log(a) // ReferenceError: a is not defined (오류 발생)
console.log(b) // ReferenceError: b is not defined (오류 발생)

let a
const b = undefined

console.log(a) // output : undefined
console.log(b) // output : undefined

2. 블록 레벨 스코프

블록(if문, for문, 함수 등)에서 할당 된 변수는 해당 블록의 지역 변수로 인정된다.

let ex = 1;
console.log(ex) // output : 1

if(true){
	let ex = 20;
  	let ex2 = 'a';
  	console.log(ex)
}

console.log(ex) // output : 20
console.log(ex2) // ReferenceError: ex2 is not defined (오류 발생)

1. let

1. 재할당 / 재선언

let은 재할당은 가능하지만, 재선언은 불가능하다.

let ex = 0;
ex = 'abc'

console.log(ex) // output : 'abc'

let ex = 0 // SyntaxError: Identifier 'ex' has already been declared. (오류 발생)

2. const

1. 재할당/ 재선언

const는 재할당도, 재선언도 전부 불가능하다. 단, 객체/배열 내의 값은 변경이 가능하다. (주소를 할당하기 때문!)

if(true){
	const ex = 1;
	ex = 1 // TypeError: Assignment to constant variable. (오류 발생)

	console.log(ex) // output : 1
}

if(true){
  const ex = [2, 2, 3]
  
  ex = [2,3,4] // TypeError: Assignment to constant variable. (오류 발생)
  
  ex[0] = 1 
  console.log(ex) // output : [1, 2, 3]
}

2. 선언과 할당

또한, const는 선언과 초기화를 동시에 해야하는 특징이 있다.

const a // SyntaxError: Missing initializer in const declaration. 
const b = 1;

다음과 같이 선언과 초기화를 동시에 해주지 않으면 오류를 뿜어내게 된다.

그래서?

ES6에서 var의 문제점들을 해결하기 위해 나온것이 let, const 키워드인만큼, var 보다는 let이나 const를 사용하는 것이 더 좋은 습관이 될 수 있다.

profile
안녕하세요, Blog 2022.06 ~

0개의 댓글