html과 javascript - let, var, const

정세형·2023년 2월 16일
0

javascript

목록 보기
28/30

var, let, const은 모두 JavaScript에서 변수를 선언하는 데 사용되지만, 중요한 차이점이 있습니다.

var(legacy)

var은 함수 스코프를 가지며 값을 재할당할 수 있으므로 선언된 함수 내 어디서든 접근할 수 있습니다. 또한 var 변수의 값을 언제든지 재할당할 수 있습니다.

let

반면에 let은 블록 스코프를 가지며 값을 재할당할 수 있습니다. 따라서 블록 내에서만 접근할 수 있습니다. var와 유사하지만 더 나은 스코프를 제공하여 코드에서 버그를 방지할 수 있습니다.

const

const는 또한 블록 스코프를 가지며 값을 재할당할 수 없습니다. 따라서 변수를 선언할 때 값을 할당해야 하며 이후에는 값을 변경할 수 없습니다. const 변수의 값을 재할당하려고 하면 TypeError가 발생합니다.

다음은 var, let, const 간의 차이점을 설명하는 예제입니다.

function example() {
  var x = 5;
  let y = 10;
  const z = 15;

  if (true) {
    var x = 20;
    let y = 25;
    const z = 30;
  }

  console.log(x); // 20
  console.log(y); // 10
  console.log(z); // 15
}

example();

이 예제에서 var x는 두 번 선언되었으며, 두 번째 선언은 값을 20으로 재할당합니다. 이는 var이 함수 스코프를 가지기 때문에 두 번째 var x 선언이 실제로 원래 x 변수를 수정하기 때문입니다.

let y도 두 번 선언되지만, 두 번째 선언은 let이 블록 스코프를 가지기 때문에 원래 y 변수의 값을 변경하지 않습니다.

const z는 재할당할 수 없으므로 두 번째 const z 선언은 TypeError를 발생시킵니다.

var, let, and const are all used to declare variables in JavaScript, but they have some important differences.

var(legacy)

var is function-scoped and can be reassigned, which means that it can be declared and accessed anywhere within the function in which it's declared. Additionally, you can reassign the value of a var variable at any time.

let

let, on the other hand, is block-scoped and can be reassigned, which means that it can only be accessed within the block in which it's declared. It's similar to var in that you can reassign its value, but it provides better scoping, which can help avoid bugs in your code.

const

const is also block-scoped but cannot be reassigned. This means that you must assign a value to a const variable when you declare it, and you cannot change its value later on in your code. If you try to reassign the value of a const variable, you'll get a TypeError.

Here's an example that illustrates the differences between var, let, and const:

function example() {
  var x = 5;
  let y = 10;
  const z = 15;

  if (true) {
    var x = 20;
    let y = 25;
    const z = 30;
  }

  console.log(x); // 20
  console.log(y); // 10
  console.log(z); // 15
}

example();

In this example, var x is declared twice, and the second declaration reassigns its value to 20. This is because var is function-scoped, so the second declaration of var x is actually modifying the original x variable.

let y is also declared twice, but the second declaration does not affect the value of the original y variable because let is block-scoped.

const z cannot be reassigned, so the second declaration of const z will throw a TypeError.

profile
👨‍💻github.com/pos1504 💌pos1504@gmail.com 🙋‍♂️https://www.linkedin.com/in/%EC%84%B8%ED%98%95-%EC%A0%95-68067b287/

0개의 댓글