본문 바로가기
FrontEnd/Javascript

[JS] Javascript의 var, let, const의 차이

by pplucy 2021. 9. 15.

 

var, let, const는 모두 자바스크립트의 변수 선언방식이지만 각각 차이점들이 존재한다.

 

[1] var

 

 

1
2
3
4
5
var userId = 'hahaha'
console.log(userId); // --- hahaha
 
var userId = 'hehehe'
console.log(userId);  // --- hehehe
cs

 

 

 

: var의 경우 여러번 선언이 가능하다.

이부분이 var사용에 있어 가장 큰 단점이라고 할 수 있다.

같은 변수명으로 여러번 변수선언이 가능하기 때문에 코드가 길어지고 복잡해질 수록 변수를 파악하기 힘들고

값이 수 없이 바뀔 수 있기 때문에 굉장히 불편하다. 

 

+ var로 선언된 변수는 선언과 동시에 초기화가 된다.  호이스팅으로 인한 상황을 예로 들어 보자면

var는 선언된 변수를 선언문 이전에 참조할 수가 있는데

console.log(userId);  // undefined

var userId;

console.log(userId); // undefined

userId = 'hahaha'.     // hahaha

이런 식으로 선언하게 되면 초기화는 진행됐지만 값이 할당되지 않았기 때문에

 userId는 undefined로 뜨게 되고

userId = 'hahaha' 형태로 값을  할당해주고 나면 userId는 'hahaha'로 실행된다.

 

 

 

 

[2] let

 

1
2
3
4
5
6
let userId = 'hahaha';
console.log(userId); // hahaha
 
let userId = 'hehehe'; // --- XXX
console.log(userId);

userId = 'hihihi';
console.log(userId) // hihihi
 
cs

 

: let은 변수의 재

+ let으로 선언된 변수는 선언과 동시에 초기화가 진행되지 않고

var와 달리 let은 선언된 변수를 선언문 이전에 참조할 수가 없다. 

console.log(userId);  // Error: Uncaught ReferenceError: userId is not defined

let userId;

만약 이런 식으로 선언하게 되면 userId가 선언만 되었지 초기화조차 진행되지 않았기에 에러가 발생한다.

 

console.log(userId);  // Error: Uncaught ReferenceError: userId is not defined

let userId;

console.log(userId); // undefined

userId = 'hahaha'

console.log(userId); // hahaha

 

[3] const

1
2
3
4
5
6
7
8
9
const userId = 'hahaha';
console.log(userId);
 
const userId = 'hehehe'// ---- XXX
console.log(userId);
 
userId = 'hihihi';
console.log(userId); // ---- XXX
 
cs

 

: const는 var, let과 달리 변수의 재선언과 재할당이 모두 불가하다.

'FrontEnd > Javascript' 카테고리의 다른 글

[JS] Javascript의 Promise  (0) 2021.01.22
[JS] Javascript의 비동기(asynchronous)  (0) 2021.01.22
[JS] Javascript의 함수(Function)  (0) 2021.01.21
[JS] Javascript의 배열(array)  (0) 2021.01.19
[JS] Javascript의 statement  (0) 2021.01.19

댓글