Variables, hoisting, and expressions
These language basics often appear together in interview questions. The useful habit is to separate when a name can be used from whether its value can change.
var, let, and const
Section titled “var, let, and const”var can be declared again in the same function and is scoped to its function. let and const are scoped to the nearest block, such as the body of an if statement. A let binding can be reassigned; a const binding cannot.
var count = 1;var count = 2; // allowed
let score = 1;score = 2; // allowed// let score = 3; // SyntaxError in the same scope
const limit = 10;// limit = 11; // TypeErrorconst prevents reassignment of the binding, not mutation of an object held by it:
const settings = { theme: 'light' };settings.theme = 'dark'; // allowed// settings = {}; // not allowedPrefer const when you do not reassign a binding, let when you do, and avoid var in modern code unless you specifically need its older scoping behavior.
What hoisting means
Section titled “What hoisting means”Hoisting describes how declarations are processed before the code runs. It does not mean every variable has a usable value before its line.
console.log(label); // undefinedvar label = 'ready';This behaves roughly like the declaration is set up first and the assignment stays where it was:
var label;console.log(label);label = 'ready';let and const bindings are also established at the start of their block, but cannot be accessed before their declaration executes. That period is called the temporal dead zone:
// console.log(mode); // ReferenceErrorlet mode = 'fast';Function declarations can be called before their definition:
sayHello();
function sayHello() { console.log('Hello');}Function expressions and arrow functions follow the rules of their variable binding, so calling them before initialization fails:
// greet(); // ReferenceErrorconst greet = () => console.log('Hi');Read a ternary carefully
Section titled “Read a ternary carefully”A ternary has the form condition ? valueWhenTrue : valueWhenFalse. For b ? !b : b, either branch evaluates to false whenever b is a boolean:
b |
Condition | Chosen expression | Result |
|---|---|---|---|
true |
true | !b |
false |
false |
false | b |
false |
const b = true;const result = b ? !b : b;console.log(result); // falseThe expression does not mutate b; it computes a value. For anything less direct, use an if statement to make the branches easier to inspect.
Quick checks
Section titled “Quick checks”- Why can
varbe read before its assignment butletcannot? - Can a property of an object declared with
constchange? - What does
false ? 1 : 2evaluate to?
Answers: var is initialized to undefined during declaration setup; const protects the binding, not the object; and the last expression evaluates to 2.