Skip to content

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 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; // TypeError

const prevents reassignment of the binding, not mutation of an object held by it:

const settings = { theme: 'light' };
settings.theme = 'dark'; // allowed
// settings = {}; // not allowed

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

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); // undefined
var 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); // ReferenceError
let 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(); // ReferenceError
const greet = () => console.log('Hi');

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); // false

The expression does not mutate b; it computes a value. For anything less direct, use an if statement to make the branches easier to inspect.

  1. Why can var be read before its assignment but let cannot?
  2. Can a property of an object declared with const change?
  3. What does false ? 1 : 2 evaluate to?

Answers: var is initialized to undefined during declaration setup; const protects the binding, not the object; and the last expression evaluates to 2.