JavaScript Variables - Exercise 3
Block-scoped declarations keep a name available only inside the nearest pair of braces.
let message = "outside";
{
let message = "inside";
console.log(message); // inside
}
console.log(message); // outsideconst prevents reassignment of the binding, but it does not freeze the object referenced by that binding.
const settings = { theme: "light" };
settings.theme = "dark";
console.log(settings.theme); // dark
// settings = {}; // TypeErrorThe declaration is prepared before execution, but its assignment happens where the code reaches it.
console.log(count); // undefined
var count = 3;
console.log(count); // 3A let binding exists before its declaration line, but reading it before initialization throws a ReferenceError.
// console.log(score); // ReferenceError
let score = 10;
console.log(score);Shadowing occurs when an inner declaration uses the same name as a declaration in an outer scope.
const label = "global";
function showLabel() {
const label = "local";
return label;
}
console.log(showLabel()); // local
console.log(label); // globalA returned function can keep access to variables from the scope where it was created.
function createCounter() {
let count = 0;
return () => ++count;
}
const next = createCounter();
console.log(next()); // 1
console.log(next()); // 2Array destructuring can assign the values on the right to the bindings on the left in one statement.
let first = "A";
let second = "B";
[first, second] = [second, first];
console.log(first, second); // B APrefer const when a binding will not be reassigned, and use let when reassignment is required. Reserve var mainly for legacy code.
const siteName = "Simply JavaScript";
let visits = 0;
visits += 1;