백엔드

var, let, const 차이점

_민영 2023. 4. 3. 13:05

< var >

> var의 scope

  • var 선언은 전역 범위 혹은 함수 범위로 지정된다.
  • var 변수가 함수 외부에서 선언될 때의 범위는 전역이다.
  • var 변수가 함수 내에서 선언될 때의 범위는 함수이다.
var test = "test";

function helloFunction() {
    var hello = "hello";
}

console.log(hello); // ReferenceError: hello is not defined

 

 

 

> var 변수는 같은 범위 내에서라면 재선언, 업데이트가 될 수 있다.

var hello = "hello";
var hello = "hello world";

console.log(hello); // hello world
var hello = "hello";
hello = "hello world";

consolo.log(hello); // hello world

 

 

 

> var의 호이스팅

  • var 변수의 경우 호이스팅 시 undefined로 변수를 초기화한다.
    (호이스팅: 인터프리터가 변수와 함수의 메모리 공간을 선언 전에 미리 할당하는 것)
console.log(num); // undefined
var num; // 선언
num = 6; // 초기화

 

 

 

> var 예시 코드

var hello = "hello";

if (true) {
    var hello = "hello world";
}

console.log(hello); // hello world

 

 

  • if 구문 안에서 새로운 변수를 사용했지만, 기존 변수의 데이터가 업데이트되었다.
  • if 구문 안의 scope는 전역(global)과 동일하게 취급받았다.

 

-> var의 문제점을 해결할 수 있는 let, const가 등장

 

 

 

 

 

< let >

> let의 scope

  • let 변수는 선언된 해당 블록 내에서만 사용이 가능하다.
let test = "test";

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

console.log(hello); // ReferenceError: hello is not defined

 

 

 

> let은 업데이트될 수 있지만, 재선언은 불가능하다.

let hello = "hello";
hello = "hello world";

console.log(hello); // hello world
let hello = "hello";
let hello = "hello world"; // SyntaxError: Identifier 'hello' has already been declared

console.log(hello);
let hello = "hello";

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

console.log(hello); // hello

 

 

 

> let의 호이스팅

  • var와 달리 호이스팅 시 undefined로 변수를 초기화하지 않는다.
  • 따라서 변수의 초기화를 수행하기 전에 읽는 코드가 먼저 나타나면 예외가 발생한다.
console.log(num); // ReferenceError: Cannot access 'num' before initialization
let num;
num = 6;

 

 

 

 

 

 

 

< const >

> const의 scope

  • let 변수와 마찬가지로 const 변수도 선언된 블록 범위 내에서만 접근이 가능하다.
const test = "test";

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

console.log(hello); // ReferenceError: hello is not defined

 

 

 

> const는 업데이트, 재선언 모두 불가능하다.

  • 따라서 모든 const 선언은 선언하는 당시에 초기화해야 한다.
const hello = "hello";
hello = "hello world"; // TypeError: Assignment to constant variable
const hello = "hello";
const hello = "hello world"; // SyntaxError: Identifier 'hello' has already been declared

 

 

  • const 개체는 업데이트할 수 없지만, 개체의 속성은 업데이트할 수 있다.
const hello = {
    msg: "hello",
    num: 3
}

// 불가능
hello = {
    message: "hello world",
    number: 5
} // TypeError: Assignment to constant variable

// 가능
hello.msg = "HELLO";
console.log(hello.msg); // HELLO

 

 

 

> const의 호이스팅

  • let과 마찬가지로 호이스팅 시 undefined로 변수를 초기화하지 않는다.
  • 따라서 변수의 초기화를 수행하기 전에 읽는 코드가 먼저 나타나면 예외가 발생한다.
console.log(num); // ReferenceError: Cannot access 'num' before initialization
const num = 6;

 

 

 

 

 

 

 

< var vs. let vs. const >

  • var는 사용하지 않는 편이 좋다.
  • 변수 선언에는 기본적으로 const를 사용하고 let은 재할당이 필요한 경우에 한정해 사용하는 것이 좋다.
  • 객체를 재할당하는 경우는 생각보다 흔하지 않기 때문에 const 키워드를 사용하면 의도치 않은 재할당을 방지해주기 때문에 보다 안전하다.

 

 

 

 

< 총정리 >

  • var 선언은 전역 범위 또는 함수 범위이며, let과 const는 블록 범위이다.
  • var 변수는 범위 내에서 업데이트 및 재선언이 가능하다. let 변수는 업데이트는 가능하지만 재선언은 불가능하다. const 변수는 업데이트 및 재선언 모두 불가능하다.
  • 세 가지 모두 최상위로 호이스팅된다. 하지만 var 변수만 undefined로 초기화되고, let과 const 변수는 초기화되지 않는다.
  • var와 let은 초기화하지 않은 상태에서 선언할 수 있지만, const는 선언 중에 초기화해야 한다.