What are the different ways to declare variables in JavaScript and what are their differences?

👨‍💻 Frontend Developer 🟢 Almost Certain 🎚️ Easy
#JavaScript #JS Basics #Data Types

Short Answer

There are three ways to declare variables in JavaScript:

  • var
  • let
  • const

The main differences relate to scope, reassignment, and hoisting.


Detailed Comparison

Featurevarletconst
ScopeFunctionBlockBlock
ReassignmentYesYesNo
RedeclarationYesNoNo
HoistingYes (uninitialized)Yes (but in TDZ)Yes (but in TDZ)
InitializationCan be laterCan be laterMust be immediate

What is TDZ?

Temporal Dead Zone is the period between variable creation and its initialization when accessing the variable throws an error.

console.log(a); // ReferenceError
let a = 10;

Examples

var — outdated but still works

function testVar() {
  if (true) {
    var message = "Hello from if";
  }
  console.log(message); // works! → "Hello from if"
}

let — preferred for mutable values

function testLet() {
  if (true) {
    let message = "Hello from if";
    console.log(message); // "Hello from if"
  }
  // console.log(message); // ReferenceError
}

const — for constants

const PI = 3.14;
PI = 3.1415; // TypeError: Assignment to constant variable.

Important: const prohibits changing the reference, not the object it points to:

const user = { name: "Alex" };
user.name = "Ivan"; // This works!

When to use which?

  • Use const by default.
  • Use let if you expect to reassign.
  • Avoid var unless maintaining legacy code.

Task 1: What will be logged?

function test() {
  console.log(a);
  var a = 5;
}
test();
Answer `undefined` — the variable is hoisted but initialized later.

Task 2: What happens?

{
  console.log(b);
  let b = 10;
}
Answer ReferenceError — accessed before initialization (TDZ).

Additional Tasks

Task 3: What will be logged?

let x = 10;
{
  let x = 20;
  console.log(x);
}
console.log(x);
Answer 20 and 10 — the `x` variables belong to different block scopes.

Task 4: What happens?

console.log(typeof undeclaredVar);
console.log(undeclaredVar);
var undeclaredVar = 42;
Answer `undefined` and `undefined` — the variable is hoisted but initialized later.

Task 5: What happens at runtime?

if (true) {
  const a = 5;
}
console.log(a);
Answer ReferenceError — `a` is block scoped and inaccessible outside.

Task 6: Can you redeclare a variable?

let name = "Aleksandr";
let name = "Evgeniya";
Answer No — SyntaxError: Identifier 'name' has already been declared.

Summary

Questions about var, let, and const are a classic in interviews.
It’s important not just to memorize but to understand the differences in scope, reassignment, and hoisting.
In real-world development, prefer const and let, and avoid var.


Want more interview prep articles?
Follow EasyAdvice, bookmark the site, and level up every day 💪