JavaScript let and const


JavaScript에서 letconst는 변수를 선언하는 두 가지 새로운 방법입니다. 이들은 var와 비교하여 여러 가지 장점을 제공합니다. 여기서는 letconst의 사용법과 특징, 그리고 var와의 차이점을 자세히 설명하겠습니다.

1. let 키워드

let은 블록 스코프를 가지는 변수 선언 방식입니다.

1.1 블록 스코프

let으로 선언된 변수는 코드 블록 내에서만 유효합니다.

if (true) {
  let x = 10;
  console.log(x); // 10
}
console.log(x); // ReferenceError: x is not defined

1.2 재할당 가능

let으로 선언된 변수는 재할당이 가능합니다.

let x = 10;
x = 20; // No error
console.log(x); // 20

1.3 변수 호이스팅

let으로 선언된 변수도 호이스팅되지만, 초기화가 되지 않아서 선언 전에 사용하면 에러가 발생합니다.

console.log(x); // ReferenceError: x is not defined
let x = 10;

2. const 키워드

const는 상수 선언 방식으로, 선언된 변수는 재할당할 수 없습니다.

2.1 블록 스코프

const도 블록 스코프를 가집니다.

if (true) {
  const y = 10;
  console.log(y); // 10
}
console.log(y); // ReferenceError: y is not defined

2.2 재할당 불가

const로 선언된 변수는 재할당할 수 없습니다.

const y = 10;
y = 20; // TypeError: Assignment to constant variable.

2.3 초기화 필수

const로 선언된 변수는 반드시 선언과 동시에 초기화해야 합니다.

const z; // SyntaxError: Missing initializer in const declaration
z = 10;

3. letconst의 비교

3.1 스코프

둘 다 블록 스코프를 가집니다. 이는 var와의 주요 차이점입니다. var는 함수 스코프를 가집니다.

if (true) {
  var a = 10;
  let b = 20;
  const c = 30;
}
console.log(a); // 10
console.log(b); // ReferenceError: b is not defined
console.log(c); // ReferenceError: c is not defined

3.2 재할당

  • let은 재할당이 가능합니다.
  • const는 재할당이 불가능합니다.
let a = 10;
a = 20; // No error

const b = 10;
b = 20; // TypeError: Assignment to constant variable.

4. var와의 차이점

4.1 스코프

  • var는 함수 스코프를 가집니다.
  • letconst는 블록 스코프를 가집니다.
function test() {
  var x = 1;
  if (true) {
    var x = 2; // Same variable!
    console.log(x); // 2
  }
  console.log(x); // 2
}

function test() {
  let y = 1;
  if (true) {
    let y = 2; // Different variable
    console.log(y); // 2
  }
  console.log(y); // 1
}

4.2 호이스팅

  • var로 선언된 변수는 선언과 초기화가 호이스팅됩니다.
  • letconst로 선언된 변수는 호이스팅되지만, 초기화가 호이스팅되지 않아 선언 전에 사용할 수 없습니다.
console.log(a); // undefined
var a = 10;

console.log(b); // ReferenceError: b is not defined
let b = 10;

console.log(c); // ReferenceError: c is not defined
const c = 10;

5. 객체와 배열의 const 사용

const는 변수 자체를 변경할 수 없도록 하지만, 객체나 배열의 경우 그 안의 내용은 변경할 수 있습니다.

const obj = { name: 'John' };
obj.name = 'Doe'; // No error

const arr = [1, 2, 3];
arr.push(4); // No error

하지만 객체나 배열 자체를 재할당하려고 하면 오류가 발생합니다.

const obj = { name: 'John' };
obj = { name: 'Doe' }; // TypeError: Assignment to constant variable.

const arr = [1, 2, 3];
arr = [4, 5, 6]; // TypeError: Assignment to constant variable.

결론

  • let: 블록 스코프 변수를 선언할 때 사용. 재할당 가능.
  • const: 블록 스코프 상수를 선언할 때 사용. 재할당 불가. 객체나 배열의 경우 내용은 변경 가능하지만, 변수 자체는 변경 불가.
  • var: 함수 스코프 변수를 선언할 때 사용. 호이스팅 시 예상치 못한 결과를 초래할 수 있으므로 가능한 사용을 피하는 것이 좋음.

letconstvar에 비해 더 안전하고 예측 가능한 코드를 작성할 수 있게 해줍니다. 일반적으로 변수를 선언할 때는 변경될 가능성이 없는 경우 const를 사용하고, 변경이 필요한 경우에만 let을 사용하는 것이 좋습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *