var 키워드를 사용하여 선언된 변수는 해당 변수가 생성된 함수로 범위가 지정되며, 함수 외부에서 생성된 경우 전역 개체로 지정됩니다. let과 const는 블록 범위입니다. 즉, 가장 가까운 중괄호(함수, if-else 블록 또는 for 루프) 내에서만 액세스할 수 있습니다.
function foo() { // All variables are accessible within functions. var bar = 'bar'; let baz = 'baz'; const qux = 'qux'; console.log(bar); // bar console.log(baz); // baz console.log(qux); // qux } console.log(bar); // ReferenceError: bar is not defined console.log(baz); // ReferenceError: baz is not defined console.log(qux); // ReferenceError: qux is not defined if (true) { var bar = 'bar'; let baz = 'baz'; const qux = 'qux'; } // var declared variables are accessible anywhere in the function scope. console.log(bar); // bar // let and const defined variables are not accessible outside the block they were defined in. console.log(baz); // ReferenceError: baz is not defined console.log(qux); // ReferenceError: qux is not defined
var를 사용하면 변수를 호이스팅할 수 있습니다. 즉, 변수가 선언되기 전에 코드에서 참조할 수 있습니다. let과 const는 이를 허용하지 않고 대신 오류를 발생시킵니다.
console.log(foo); // undefined var foo = 'foo'; console.log(baz); // ReferenceError: can't access lexical declaration 'baz' before initialization let baz = 'baz'; console.log(bar); // ReferenceError: can't access lexical declaration 'bar' before initialization const bar = 'bar';
var로 변수를 다시 선언하면 오류가 발생하지 않지만, let과 const에서는 오류가 발생합니다.
var foo = 'foo'; var foo = 'bar'; console.log(foo); // "bar" let baz = 'baz'; let baz = 'qux'; // Uncaught SyntaxError: Identifier 'baz' has already been declared
let과 const는 변수 값을 재할당할 수 있지만 const는 그렇지 않다는 점에서 다릅니다.
// This is fine. let foo = 'foo'; foo = 'bar'; // This causes an exception. const baz = 'baz'; baz = 'qux';
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3