"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > Let, Const 및 Var 개요: 주요 차이점 설명

Let, Const 및 Var 개요: 주요 차이점 설명

2024-08-07에 게시됨
검색:248

An Overview of Let, Const, and Var: Key Differences Explained

JavaScript에서 let, const, var의 실제 사용법을 사용하고 이해할 때가 있었지만 말로 설명하는 것이 어려웠습니다. 유사한 곤경에 처한 경우 초점을 맞춰야 할 핵심 사항은 범위, 호이스팅, 재초기화 및 재할당의 차이점입니다.

범위 지정:

  • var는 함수 범위 또는 함수 외부에서 선언된 경우 전역 범위입니다.

var(함수 및 전역 범위)를 사용한 예

function varExample() {
    if (true) {
        var x = 10; // x is function-scoped
    }
    console.log(x); // Outputs: 10
}
varExample();

if (true) {
    var y = 20; // y is globally scoped because it's outside a function
}
console.log(y); // Outputs: 20
  • let 및 const는 블록 범위입니다. 즉, 선언된 블록({}로 구분) 내에서만 액세스할 수 있습니다.

let(블록 범위)의 예

function letExample() {
    if (true) {
        let x = 10; // x is block-scoped
        console.log(x); // Outputs: 10
    }
    console.log(x); // ReferenceError: x is not defined
}
letExample();

if (true) {
    let y = 20; // y is block-scoped
    console.log(y); // Outputs: 20
}
console.log(y); // ReferenceError: y is not defined

const(블록 범위)의 예

function constExample() {
    if (true) {
        const x = 10; // x is block-scoped
        console.log(x); // Outputs: 10
    }
    console.log(x); // ReferenceError: x is not defined
}
constExample();

if (true) {
    const y = 20; // y is block-scoped
    console.log(y); // Outputs: 20
}
console.log(y); // ReferenceError: y is not defined

호이스팅

호이스팅은 작업을 시작하기 전에 작업 공간을 설정하는 것과 같습니다. 당신이 부엌에서 식사 준비를 하고 있다고 상상해 보세요. 요리를 시작하기 전에 모든 재료와 도구를 손이 닿는 곳에 있도록 카운터에 놓아두세요.

프로그래밍에서 코드를 작성할 때 JavaScript 엔진은 코드를 실제로 실행하기 전에 코드를 검토하고 해당 범위의 최상위에 모든 변수와 함수를 설정합니다. 즉, 코드에서 함수와 변수를 선언하기 전에 함수와 변수를 사용할 수 있습니다.

  • 세 ​​개(var, let, const) 모두 실제로 호이스팅되었습니다. 그러나 차이점은 호이스팅 과정에서 초기화되는 방식에 있습니다.

  • var는 호이스팅되고 정의되지 않은 상태로 초기화됩니다.

console.log(myVar); // Outputs: undefined
var myVar = 10;

  • let 및 const는 호이스팅되지만 초기화되지는 않습니다. 이는 블록 시작부터 선언이 나타날 때까지 "일시적 데드존"에 있음을 의미합니다.
console.log(myLet);
// ReferenceError: Cannot access 'myLet' before initialization
let myLet = 10;
console.log(myConst); 
// ReferenceError: Cannot access 'myConst' before initialization
const myConst = 20;

재할당 및 재초기화:

  • var는 다시 초기화(다시 선언)하고 재할당(새 값 할당)할 수 있습니다. ### var를 사용한 예
var x = 10;
x = 20; // Reassignment
console.log(x); // Outputs: 20

var x = 30; // Reinitialization
console.log(x); // Outputs: 30

  • let은 동일한 범위 내에서 다시 초기화될 수 없지만 재할당될 수 있습니다.
let y = 10;
y = 20; // Reassignment
console.log(y); // Outputs: 20

let y = 30; // SyntaxError: Identifier 'y' has already been declared
  • const는 재할당될 수 없습니다. 선언 시 초기화되어야 합니다. 그러나 const가 객체 또는 배열인 경우 객체 또는 배열의 내용(속성 또는 요소)을 수정할 수 있습니다. ### const의 예
const z = 10;
z = 20; // TypeError: Assignment to constant variable.

const z = 30; // SyntaxError: Identifier 'z' has already been declared

const 객체의 예

const obj = { a: 1 };
obj.a = 2; // Allowed, modifies the property
console.log(obj.a); // Outputs: 2

obj = { a: 3 }; // TypeError: Assignment to constant variable.

const 배열의 예

const arr = [1, 2, 3];
arr[0] = 4; // Allowed, modifies the element
console.log(arr); // Outputs: [4, 2, 3]

arr = [5, 6, 7]; // TypeError: Assignment to constant variable.
릴리스 선언문 이 기사는 https://dev.to/bazeng/an-overview-of-let-const-and-var-key-differences-explained-1ihi?1에 복제되어 있습니다. 침해가 있는 경우에는 Study_golang@163으로 문의하시기 바랍니다. .com에서 삭제하세요
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3