[JavaScript] let, var, const 차이점
var
var는 const와 let과 달리 중복 선언이 여러번 가능하다.
var str1 = 'hello!';
console.log('str1 : ', str1); // 출력 >> str1 : hello!
str1 = 'hi!';
console.log('str1 : ', str1); // 출력 >> str1 : hi!
var str1 = 'bye~';
console.log('str1 : ', str1); // 출력 >> str1 : bye~
재할당, 재선언 모두 에러없이 출력된다.
var는 변수를 유연하게 사용할 수 있다는 장점이 있지만,
위에서 선언한 변수를 생각하지 못하고 재할당하거나 재선언하는 실수를 할 수 있다!
그렇기에 요즘은 var를 사용하기 보다는 let을 사용하는 것을 선호한다.
function test() {
var str1 = 'function!';
console.log('function : ', str1);
}
function test2() {
str1 = 'function!';
console.log('test2 : ', str1);
}
var str1 = 'hello!';
console.log('str1 : ', str1);
test();
console.log('after test : ', str1);
test2();
console.log('after test2 : ', str1);
위 코드를 실행하면
test 함수 내부에서는 내부에서 선언한 값으로 출력되고 전역변수인 str1에는 영향을 주지 않고 그대로 'hello!'로 출력된다.
test2 함수에서는 재할당으로 전역변수인 str1에도 영향을 주는 것을 볼 수 있다.
const
const와 let은 블록 스코프로 유사하지만
const는 재할당, 재선언이 불가능하다.
const str2 = 'hello!';
console.log('str2 : ', str2); // 출력 >> str2 : hello!
str2 = 'hi!';
위 코드를 실행해보면
TypeError: Assignment to constant variable.
상수 변수 할당 오류가 발생한다. const는 재할당이 불가능하기 때문이다.
const str2 = 'hello!';
console.log('str2 : ', str2); // 출력 >> str2 : hello!
const str2 = 'hi!';
위 코드를 실행해보면
SyntaxError: Identifier 'str1' has already been declared
이미 선언되어있다는 오류가 발생한다. 이는 const가 재선언이 불가능하기 때문이다.
function test() {
const str2 = 'function!';
console.log('test : ', str2);
}
function test2() {
str2 = 'function!';
console.log('test2 : ', str2);
}
const str2 = 'hello!';
console.log('str2 : ', str2);
test();
console.log('after test : ', str2);
test2();
console.log('after test2 : ', str2);
const는 함수 내부에서는 재선언이 가능하지만 재할당은 안된다.
또한 함수 안에서 재선언한 것이 함수 외부에 영향을 주지 않는다.
let
let은 const와 같이 재선언은 불가능하지만, 재할당은 가능하다.
let str3 = 'hello!';
console.log('str3 : ', str3); // 출력 >> str3 : hello!
str2 = 'hi!';
console.log('str3 : ', str3); // 출력 >> str3 : hi!
재할당이 가능하기 때문에 위 코드는 오류없이 잘 실행된다.
반면에 const와 같이 재선언은 불가능하기 때문에
let str3 = 'hello!';
console.log('str3 : ', str3); // 출력 >> str3 : hello!
let str3 = 'hi!';
console.log('str3 : ', str3);
SyntaxError: Identifier 'str2' has already been declared
이미 선언되어있다는 오류가 발생한다.
function test() {
let str3 = 'function!';
console.log('test : ', str3);
}
function test2() {
str3 = 'function!';
console.log('test2 : ', str3);
}
let str3 = 'hello!';
console.log('str3 : ', str3);
test();
console.log('after test : ', str3);
test2();
console.log('after test2 : ', str3);
let은 var와 같이 재선언도 재할당도 영향을 받지 않는다.
📢📢📢📢
코드 내 상수로 사용되는 변수의 경우에는 const,
재할당이 필요한 변수의 경우에는 let을 사용하는게 좋다!
[출처]