티스토리 뷰

🌈 JavaScript

var VS let VS const

James Wetzel 2023. 10. 31. 11:42
728x90
반응형
  scope(범위) value(값)
ver globally-scoped variables 변경 가능
let block-scoped local variables 변경 가능
cost block-scoped local variables 변경 불가

 

var x = 1;

if (x === 1) {
  var x = 2;

  console.log(x);
  // Expected output: 2
}

console.log(x);
// Expected output: 2

 

let x = 1;

if (x === 1) {
  let x = 2;

  console.log(x);
  // Expected output: 2
}

console.log(x);
// Expected output: 1

 

const number = 42;

try {
  number = 99;
} catch (err) {
  console.log(err);
  // Expected output: TypeError: invalid assignment to const `number'
  // (Note: the exact output may be browser-dependent)
}

console.log(number);
// Expected output: 42
728x90
반응형