관리 메뉴

FU11M00N

[ ES6 Script ] JS let 과 const 본문

Programming/Javascript

[ ES6 Script ] JS let 과 const

호IT 2021. 2. 15. 20:55

- ES 4,5의 해결책

 

ES4,5시대에는 var키워드로 변수와 상수를 선언했었습니다.

 

하지만

var를 사용할 경우, 전반적으로 코드가 어떻게 작동될지 직관적으로 예측하기 어려운 경우가 자주 발생합니다.

hosting 개념. https://nevertrustbrutus.tistory.com/335

 

그래서 ES6에서는 let과 const를 사용하여 변수와 상수를 선언해야합니다.

변수는 let 선언자, 상수는 const 선언자를 이용하면 됩니다.

 

 

 

 

- let

 

이번에는 let 선언자를 이용해 선언하면 아래와 같습니다.

let test = 1;
console.log(test);
let test = 2;
console.log(test);

 

 

let 변수는 var 변수와 다르게 재선언이 되지 않습니다.

 

2. const

 

const 는 호이스팅이 불가능하기때문에 에러가 발생하지않습니다.

아래의 예제는 "undefined" 가 출력됩니다.

 

console.log(test)
var test=1;

 

 

 

이는 자바스크립트가 변수 선언을 console.log() 위에 있는 것 처럼 내부적으로 실행합니다.

이것이 호이스팅 입니다.

 

 

 

마치 아래 코드와 같이 동작합니다.

 

var test;
console.log(test);
test=1;

 

하지만 const 선언자를 사용하면 할당하면 아래와 같이 오류가 발생합니다.

 

 

 

console.log(test);
const test=1;

 

 

const 선언에 초기화가 이루어지지 않았다고 알려주는것입니다.

 

 

 

- let 과 const 같은점

 

let과 const는 둘 다 재선언이 되지 않습니다.

let test = 1;
console.log(test);
let test = 2;
console.log(test);

 

let

 

const test = 1;
console.log(test);
const test = 2;
console.log(test);

const

 

 

- let 과 const 차이점

 

 

const 는 재할당이 불가능합니다.

 

const test =1;
test=2;

 

let

 

const test3=2;
test3=2;

const

 

 

- const의 특징

 

 

만약 아래 코드와 같이 const 변수가 참조형이라면, 객체의 프로퍼티는 변경 가능합니다.

 

const hello = {
	id :1,
    name : "FU11_M00N"
}
hello.id=100;
hello.name="hojun";

console.log (hello.id, hello.name);

 

 

Comments