⚠️ JavaScript에서 `var` 사용의 숨겨진 위험: 이제 다음 단계로 넘어갈 때인 이유

PHPz
풀어 주다: 2024-09-12 18:15:14
원래의
453명이 탐색했습니다.

⚠️ The Hidden Dangers of Using `var` in JavaScript: Why It’s Time to Move On

var 키워드는 수년간 JavaScript에서 변수를 선언하는 기본 방법이었습니다. 그러나 코드에서 예상치 못한 동작을 초래할 수 있는 몇 가지 단점과 함정이 있습니다. let 및 const와 같은 최신 대안은 이러한 많은 문제를 해결하므로 대부분의 경우 변수 선언에 선호됩니다.


1️⃣ 호이스팅: var는 알기도 전에 변수를 선언합니다!

? 설명:

JavaScript에서 var 선언은 해당 범위의 맨 위로 끌어올려집니다. 즉, 선언이 나중에 코드에 나타나더라도 정의되지 않은 상태로 초기화됩니다. 이로 인해 혼란스러운 동작이 발생하고 감지하기 어려운 버그가 발생할 수 있습니다.

? 핵심 사항:

  • ? 호이스팅 실행: 변수 선언은 범위의 맨 위로 이동되지만 할당은 그렇지 않습니다.
  • ? 예기치 않은 정의되지 않은 값: 값이 할당되기 전에 변수를 사용할 수 있어 의도하지 않은 정의되지 않은 결과가 발생할 수 있습니다.

? 예:

console.log(myVar);  // undefined (hoisted but not initialized)
var myVar = 10;
console.log(myVar);  // 10
로그인 후 복사

? 설명: myVar 변수는 범위의 맨 위로 끌어올려지지만 처음에는 정의되지 않아 코드에 혼란을 일으킬 수 있습니다.

? 수정:

  • ? let 또는 const 사용: 이러한 키워드는 var와 같은 방식으로 끌어올려지지 않으므로 이 문제를 방지하는 데 도움이 됩니다.

? 수정 예:

console.log(myLet);  // ReferenceError: myLet is not defined
let myLet = 10;
console.log(myLet);  // 10
로그인 후 복사

? 설명: let을 사용하면 변수가 선언되기 전에 변수에 액세스하는 것을 방지하여 혼란과 잠재적인 버그를 줄일 수 있습니다.


2️⃣ 함수 범위와 블록 범위: var는 블록에서 누출될 수 있습니다!

? 설명:

var의 주요 결함 중 하나는 블록 범위가 아닌 함수 범위라는 것입니다. 이는 루프, if 문 또는 기타 블록 내부에 선언된 변수가 해당 블록에만 국한되지 않고 외부에서 액세스할 수 있어 버그가 발생할 수 있음을 의미합니다.

? 핵심 사항:

  • ? 함수 범위: var는 루프나 if 문과 같이 블록 내부에 선언된 경우에도 가장 가까운 함수로 범위가 지정됩니다.
  • ? 변수 누출: 이로 인해 변수가 의도치 않게 블록 외부로 누출되어 예측할 수 없는 동작이 발생할 수 있습니다.

? 예:

if (true) {
  var blockVar = "I’m accessible outside this block";
}
console.log(blockVar);  // "I’m accessible outside this block"
로그인 후 복사

? 코멘트: blockVar는 if 블록 내부에서 선언되었지만 var는 블록 범위가 아닌 함수 범위이므로 블록 외부에서 여전히 액세스할 수 있습니다.

? 수정:

  • ? let 또는 const 사용: 이러한 키워드는 블록 범위이므로 정의된 블록 내에서만 액세스할 수 있습니다.

? 수정 예:

if (true) {
  let blockLet = "I’m only accessible inside this block";
}
console.log(blockLet);  // ReferenceError: blockLet is not defined
로그인 후 복사

? 설명: let 또는 const를 사용하면 변수가 해당 블록에 국한되어 범위 누출을 방지할 수 있습니다.


3️⃣ 재선언 문제: var를 사용하면 같은 변수를 두 번 선언할 수 있습니다!

? 설명:

var를 사용하면 동일한 범위에서 동일한 변수를 실수로 다시 선언하여 이전 값을 덮어쓸 수 있습니다. 이는 특히 변수 이름이 실수로 재사용될 수 있는 대규모 코드베이스에서 의도하지 않은 버그로 이어질 수 있습니다.

? 핵심 사항:

  • ? 변수 재선언: var를 사용하면 동일한 범위 내에서 변수를 재선언하여 잠재적으로 기존 값을 덮어쓸 수 있습니다.
  • ? 의도하지 않은 덮어쓰기: 이로 인해 특히 크거나 복잡한 기능에서 감지하기 어려운 버그가 발생할 수 있습니다.

? 예:

var name = "Alice";
var name = "Bob";  // No error, overwrites the previous value
console.log(name);  // "Bob"
로그인 후 복사

? 댓글: 두 번째 이름 선언이 첫 번째 선언을 덮어쓰므로 잠재적으로 코드에 버그가 발생할 수 있습니다.

? 수정:

  • ? let 또는 const 사용: 이 키워드는 동일한 범위에서 변수를 다시 선언하는 것을 방지하여 의도하지 않은 덮어쓰기의 위험을 줄입니다.

? 수정 예:

let name = "Alice";
let name = "Bob";  // SyntaxError: Identifier 'name' has already been declared
로그인 후 복사

? 댓글: let 또는 const를 사용하면 변수를 다시 선언하는 것을 방지하고 코드를 예측 가능하게 유지할 수 있습니다.


4️⃣ 루프의 var: 비동기 코드의 버그 가능성

? 설명:

루프에서 var를 사용하면 특히 비동기 코드로 작업할 때 변수 값이 예상치 못한 방식으로 변경될 수 있습니다. var는 블록 범위가 아닌 함수 범위이므로 비동기 콜백 내에서 액세스할 때 루프 변수에 예상치 못한 값이 포함될 수 있습니다.

? 핵심 사항:

  • ? Loop Variables: Variables declared with var inside loops are not confined to the loop block, leading to potential bugs when accessed later.
  • Asynchronous Issues: This can cause bugs in asynchronous operations like setTimeout or promises, where the loop variable might have an unexpected value.

? Example:

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000);  // Prints: 3, 3, 3 (unexpected)
}
로그인 후 복사

? Comment: Because var is not block-scoped, the loop variable i is shared across all iterations, and its final value (3) is used in each setTimeout callback.

? Fix:

  • Use let: The let keyword is block-scoped, ensuring that each iteration of the loop gets its own independent value of the loop variable.

? Example Fix:

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000);  // Prints: 0, 1, 2 (as expected)
}
로그인 후 복사

? Comment: Using let creates a new instance of i for each iteration, fixing the asynchronous callback issue and ensuring the correct values are printed.


5️⃣ var and Closures: A Source of Confusion

? Explanation:

Closures can lead to unexpected behavior when combined with var. Since var is function-scoped, its value might change in ways that are not expected when a closure captures it.

? Key Points:

  • ? Closures in JavaScript: A closure is a function that remembers its surrounding scope even after the outer function has finished executing.
  • ? Shared Variable Issues: When var is used inside a closure, the captured variable might be shared across all closures, leading to unexpected behavior.

? Example:

function createFunctions() {
  var funcs = [];
  for (var i = 0; i < 3; i++) {
    funcs.push(function() {
      console.log(i);
    });
  }
  return funcs;
}

var myFuncs = createFunctions();
myFuncs[0]();  // 3 (unexpected)
myFuncs[1]();  // 3 (unexpected)
myFuncs[2]();  // 3 (unexpected)
로그인 후 복사

? Comment: All closures are capturing the same i value because var is function-scoped, leading to unexpected results.

? Fix:

  • ? Use let: By using let, each closure captures a new instance of the loop variable, solving the problem.

? Example Fix:

function createFunctions() {
  var funcs = [];
  for (let i = 0; i < 3; i++) {
    funcs.push(function() {
      console.log(i);
    });
  }
  return funcs;
}

var myFuncs = createFunctions();
myFuncs[0]();  // 0
myFuncs[1]();  // 1
myFuncs[2]();  // 2
로그인 후 복사

? Comment: With let, each closure gets its own copy of i, fixing the issue and ensuring the expected values are printed.


? Conclusion: Time to Say Goodbye to var

While var was the original way to declare variables in JavaScript, it has several shortcomings that make it a poor choice in modern JavaScript development. The introduction of let and const provides better scoping, reduces the risk of bugs, and makes your code more predictable. To write cleaner and more maintainable JavaScript, it's time to move on from var and embrace let and const.

위 내용은 ⚠️ JavaScript에서 `var` 사용의 숨겨진 위험: 이제 다음 단계로 넘어갈 때인 이유의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!