Example 1 — Function scope
var is function-scoped.
JavaScript
function f() {
if (true) var x = 1;
console.log(x);
}
f();How It Works
- var ignores the if block boundary.
Scope controls where a variable name can be used. let and const are block-scoped. var is function-scoped. Nested scopes can read outer bindings.
const outer = "o";
{
const inner = "i";
console.log(outer, inner);
}var is function-scoped.
function f() {
if (true) var x = 1;
console.log(x);
}
f();let stays in the block.
{
let x = 1;
}
console.log(typeof x);Inner name hides outer.
const n = 1;
{
const n = 2;
console.log(n);
}
console.log(n);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