반응형
1. 변수 선언 차이
#1) var 변수
var을 사용하게 되면 다음과 같이 같은 이름의 변수를 한 번 더 선언해도 다른 값이 출력된다. 이는 유연한 변수 선언이 가능하지만 코드량이 많아진다면 어떻게 사용될지 파악하기 힘들고 값이 바뀔 우려가 있다.
var test = 'test1'
console.log(test) // test1
var test = 'test2'
console.log(test) // test2
#2) let, const 변수
다음처럼 같은 이름으로 변수를 선언할 경우 이미 선언된 변수라고 에러가 발생한다.
let test = 'test1'
console.log(test) // test1
let test = 'test2'
console.log(test)
// Uncaught SyntaxError: Identifier 'test' has already been declared
#3) let const 차이
다음과 같이 let은 같은이름으로 변수는 선언할 수 없지만 같은 변수에 다른 값을 재할당할 수 있다.
let test = 'test1'
console.log(test) // test1
name = 'change'
console.log(test) //change
하지만 const는 let과 달리 같은 변수에 다른 값을 재할당 할 수 없다.
const test = 'test1'
console.log(test) // test1
const test = 'test2'
console.log(test)
// Uncaught SyntaxError: Identifier 'test' has already been declared
test = 'change'
console.log(test)
//Uncaught TypeError: Assignment to constant variable.
즉 var = 재선언 재할당 가능, let 재선언 불가 재할당 가능, const 재선언, 재할당 불가이다.
2. 호이 스팅
호이 스팅이란? _참고
var, let에는 다음과 같은 호이스팅 차이가 존재한다. var은 test가 없어도 호이스팅 되어 undefined로 결과가 찍히지만 let은 호이스팅 되지 않아 에러가 발생한다.
console.log(test); // undefined
var test;
console.log(test1); // Error: Uncaught ReferenceError: test1 is not defined
let test1;
3. 마무리
기본적으로 변경이 없는 변수일 경우 const를 사용하고 재할당이 필요한 경우라면 let을 사용하는 것이 좋을 것 같다
반응형
'프로그래밍 > NodeJS' 카테고리의 다른 글
[Javascript] #6 호이스팅이란? (0) | 2020.05.25 |
---|---|
[Node.JS / Express 강의] #4 비동기 처리 란? / Promise 란? / async & await란? (0) | 2020.02.16 |
[Node.JS / Express 강의] #3 express-session, session-store 설치 및 사용하기 / 세션, 쿠키, 로그인하기 (0) | 2020.01.21 |
[Node.JS / Express 강의] #2 Express 설명 및 설치방법 (0) | 2019.11.12 |
[Node.JS / Express 강의] #1 Node.JS 설명 및 설치 방법 (0) | 2019.11.05 |