JavaScript Variables - Exercise 3

Block-scoped declarations keep a name available only inside the nearest pair of braces.

javascript

let message = "outside";
{
  let message = "inside";
  console.log(message); // inside
}
console.log(message); // outside

const prevents reassignment of the binding, but it does not freeze the object referenced by that binding.

javascript

const settings = { theme: "light" };
settings.theme = "dark";
console.log(settings.theme); // dark
// settings = {}; // TypeError

The declaration is prepared before execution, but its assignment happens where the code reaches it.

javascript

console.log(count); // undefined
var count = 3;
console.log(count); // 3

A let binding exists before its declaration line, but reading it before initialization throws a ReferenceError.

javascript

// 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.

javascript

const label = "global";
function showLabel() {
  const label = "local";
  return label;
}
console.log(showLabel()); // local
console.log(label); // global

A returned function can keep access to variables from the scope where it was created.

javascript

function createCounter() {
  let count = 0;
  return () => ++count;
}
const next = createCounter();
console.log(next()); // 1
console.log(next()); // 2

Array destructuring can assign the values on the right to the bindings on the left in one statement.

javascript

let first = "A";
let second = "B";
[first, second] = [second, first];
console.log(first, second); // B A

Prefer const when a binding will not be reassigned, and use let when reassignment is required. Reserve var mainly for legacy code.

javascript

const siteName = "Simply JavaScript";
let visits = 0;
visits += 1;