[JS] var, let, const

Minyoung's Conference·2022년 5월 14일
0

JavaScript

목록 보기
6/28
post-thumbnail

var는 function scope(변수에 접근할 수 있는 범위)를 가지고 있는 변수 선언 방식이다.

var의 경우 같은 이름으로 여러번 선언해줘도 오류가 나지 않기 때문에 위험하다. 그래서 사용을 지양하고 es6 이후에는 let, const를 사용해주어야 한다.

let : 값을 재정의할 수 있는 변수 선언 방식 (변수 : 변하는 수)

const : 값을 재정의할 수 없는 변수 선언 방식 (상수 : 변하지 않는 수)

let hello = "first hello";

hello = "second hello";

console.log(hello);

//second hello

let을 두번 써서 재정의 할 순 없다.

let hello = "first hello";

let hello = "second hello";

console.log(hello);

//SyntaxError: Identifier 'hello' has already been declared

그리고 let은 function scope가 아닌, 중괄호 scope를 가진다.

let hello = "first hello";

if (true) {
  let hello = "second hello";
  console.log(hello); //second hello
}

console.log(hello); //first hello

const는 재정의할 수 없다.

const hello = "first hello";

hello = "second hello";

console.log(hello);
// TypeError: Assignment to constant variable.

또한, 중괄호 scope를 가지고 있다.

const hello = "first hello";
if(true){
	const hello = "second hello";
    console.log(hello); //second hello
}    
console.log(hello); //first hello
profile
안녕하세요, FE 개발자 김민영입니다.

0개의 댓글