변수 선언 방식 var, let, const 의 차이점

변수 선언 방식 var, let, const 의 차이점

var 의 변수 선언 방식은 단점을 가지고 있음

var topic = 'nodejs' console.log(topic) // nodejs var topic = 'mysql' console.log(topci) // mysql

변수를 다시 선언해도 에러가 나오지 않고 각기 다른 값이 출력됩니다.

이러한 상황이 반복된다면 코드의 복잡성이 증가함에 따라 곤란한 경우가 생길 수 있다.

때문에 많은 javascript 개발자들은 이러한 문제를 방지 하기 위해 let 과 const 를 사용하여 변수를 선언하기로 하였다.

let 은 변수에 재할당이 가능하다.

let topic = 'nodejs' console.log(topic) // nodejs let topic = 'mysql' console.log(topci) // Uncaught SyntaxError: Identifier 'topic' has already been declared topic = 'ajax' console.log(topic) // ajax

const 는 변수 재선언, 재할당 모두 불가능하다.

const topic = 'nodejs' console.log(topic) // nodejs const topic = 'mysql' console.log(topci) // Uncaught SyntaxError: Identifier 'topic' has already been declared topic = 'ajax' console.log(topic) //Uncaught TypeError: Assignment to constant variable.

결론

기본적으로 변수 선언에는 const 를 사용하고, 재할당이 필요한 경우에만 let 을 사용하는 것을 추천.

- 상수와 객체는 재할당이 필요없으므로 const 를 사용한다.

*스코프(scope) : 변수 참조가 가능한 유효 범위

*재할당 : 다시 배치,배분,배포 하다.

from http://codinghatso.tistory.com/17 by ccl(A) rewrite - 2021-08-27 19:00:09