Example 1 — Block scope
let/const live inside { }.
JavaScript
{
let x = 1;
}
try { console.log(x); } catch (e) { console.log(e.name); } How It Works
- x is not visible outside the block.
- Access throws ReferenceError.
let and const are block-scoped. var is function-scoped and older. Prefer const by default, let when you must reassign, and avoid var in modern code.
const name = "Ada";
let score = 0;
score = 10;
console.log(name, score); let/const live inside { }.
{
let x = 1;
}
try { console.log(x); } catch (e) { console.log(e.name); } const stops rebinding, not property changes.
const user = { n: 1 };
user.n = 2;
console.log(user.n); Why modern code avoids var.
function f() {
if (true) var v = 1;
console.log(v);
}
f(); CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful