웹 세상/javascript
javascript var, let, const 에 대해 알아보자
여러가지이야기
2020. 5. 12. 23:28
var
- Function-level scope (fuction 단위의 scope를 가짐)
- 재선언이 가능함(동일한 변수를 중복해서 선언 가능)
- 재할당 가능함
- 코드의 길이가 길어졌을 때 원치않게 기존에 있던 변수를 다른 값으로 덮어쓰게 될 수 있다.
- ES6(ECMAScript6)부터 이를 보완해주는 let과 const가 등장한다.
var num = 10; //undefined
num; //10
var num = 20; //undefined 재선언 가능
num; //20
num = 30; //undefined 변경되는 데이터 저장 가능(재할당 가능)
num; //30
let
- Block-level scope
- 재선언 불가(이미 선언된 변수를 다시 선언할 수 없음), const와 같음
- 재할당이 가능하다(immutable).
let num1;
num1; //15
let num1 = 20;
num1; // Uncaught SyntaxError: Identifier 'num1' has already been declared
num1 = 30;
num1; //30
const
- Block-level scope
- 재선언, 재할당 모두 불가능하기 때문에 변경하지 않을 데이터를 선언할 때 사용
- 변수의 중복 선언과 값의 재지정으로 인한 오류를 줄일 수 있음
const a = "apple"
const a = "banana" //Uncaught SyntaxError: Identifier 'a' has already been declared 재선언 불가능
a = "banana" //Uncaught TypeError: Assignment to constant variable. at <anonymous>:1:3 재할당 불가능
더 필요한 공부
Function-level scope
,Block-level scope
- 호이스팅
참고한 블로그
https://poiemaweb.com/es6-block-scope
https://velog.io/@bathingape/JavaScript-var-let-const-%EC%B0%A8%EC%9D%B4%EC%A0%90