Topic 4 of 59 JavaScript Core Fundamentals Interactive Tutorial

JavaScript Variables: var, let, const, and Value Storage

23 mins read Last updated: 22 Aug 2026 14453 views
Quick Summary & Key Takeaway Target Skill Level: Beginner to Advanced ES6+

Bottom-Line Answer: JavaScript (JS) is a high-level, single-threaded, just-in-time (JIT) compiled programming language with first-class functions that conforms to the ECMAScript specification. It powers dynamic client-side web interactivity alongside HTML and CSS, and executes backend server runtimes via Node.js, Deno, and Bun.

Target Audience: Frontend developers, full-stack engineers, students & QA testers.
Prerequisites: Basic HTML semantics & fundamental CSS styling rules.
Primary Use Cases: Dynamic web UI, DOM manipulation, asynchronous REST APIs, Node.js backend services.

What is JavaScript Variables? Core Concept & Direct Summary

Core Objective & Problem Statement

What are var, let, and const in JavaScript, how do their scope and hoisting behaviors differ, and how does JavaScript manage memory heap vs stack value storage?

Direct Answer Summary

That one word —let— is the doorway to one of the most important concepts in all of programming:variables. Every app you've ever used, from Instagram to your banking app, is fundamentally about storing data and changing it. Variables are how JavaScript does that.

In this lesson, you'll learn what variables really are, the three ways to create them (var,let,const), which one you should actually use in 2025, and how JavaScript stores values behind the scenes. Let's open the box. 📦

How Does JavaScript Variables Work? In-Depth Mechanics & Architecture

What Is a Variable?

Avariable is a named container that stores a value in your program's memory.

Think of it like a labeled box:

  • 📦 Thebox= space in the computer's memory
  • 🏷️ Thelabel= the variable's name
  • 🎁 Thecontents= the value stored inside
PartWhat It Is
letThe keyword — "create a new box"
userNameThe label — how we refer to this box later
=The assignment operator — "put this inside"
"Priya"The value — the actual contents

Why do variables matter so much? Because programs are useless if they can'tremember things— your name, your score, the items in your cart. Variables are JavaScript's memory.

Declaring vs. Assigning: Two Separate Steps

Creating a variable actually involves two steps, and beginners often mix them up:

script.js
Run Online
let score;
// Step 1: DECLARATION — creating the empty box
score = 100;
// Step 2: ASSIGNMENT — putting a value inside

Or do both in one line (this is calledinitialization):

script.js
Run Online
let score = 100;
// Declare AND assign in one go ✅

What happens if you use a box before putting anything in it?

script.js
Run Online
let score;
console.log(score);
// undefined

JavaScript answers withundefined— its way of saying"the box exists, but it's empty."Remember this word; you'll see it constantly as a developer.

The Three Ways to Declare Variables

JavaScript offers three keywords:var,let, andconst. They look similar but behave very differently.

1️⃣var— The Old Way (Pre-2015)

script.js
Run Online
var city = "Mumbai";
console.log(city);
// Mumbai

varwas JavaScript'sonlyvariable keyword for 20 years. But it has quirky behaviors that cause bugs:

  • It can be re-declared— accidentally creating the same variable twice without any error:
script.js
Run Online
var city = "Mumbai";
var city = "Delhi";
// No error! 😬 The first one just vanishedconsole.log(city);     // Delhi
  • It ignores block scope— it "leaks" out of{ }blocks in ways that surprise everyone (more on scope below).

Verdict:You'll seevarin old tutorials and legacy code, so you mustrecognizeit — but don't write it in new code.

2️⃣let— The Modern, Changeable Variable (2015+)

script.js
Run Online
let points = 50;
points = 75;
// ✅ Updating is allowedconsole.log(points);  // 75

letfixesvar's problems:

  • Re-assigning is allowed✅
  • Re-declaring is blocked— JavaScript throws an error instead of silently breaking:
script.js
Run Online
let points = 50;
let points = 75;
// ❌ SyntaxError: 'points' has already been declared

This is agoodthing! The error protects you from accidentally overwriting your own data.

3️⃣const— The Locked Box 🔒

script.js
Run Online
const birthYear = 2000;
birthYear = 2001;
// ❌ TypeError: Assignment to constant variable

constcreates aconstant— once assigned, the value can never be re-assigned. Two strict rules:

  1. You must assign a value immediately:
script.js
Run Online
const country;
// ❌ SyntaxError — must initialize
const country = "India";
// ✅
  1. No re-assignment, ever.

⚠️ A famous misconception:constdoesn't makeeverythingunchangeable. For arrays and objects, thecontentscan still change — you just can't point the variable at a brand-new value:

script.js
Run Online
const cart =["shoes", "watch"];
cart.push("cap");
// ✅ Allowed — contents changed
console.log(cart);
// ["shoes", "watch", "cap"]
cart =[];
// ❌ Error — re-assignment blocked

var vs let vs const: The Complete Comparison

This is the#1 most-asked JavaScript interview question— and this table is the answer:

Featurevarletconst
Year introduced19952015 (ES6)2015 (ES6)
Can re-assign value?✅ Yes✅ Yes❌ No
Can re-declare?✅ Yes (dangerous!)❌ No❌ No
Must initialize immediately?NoNo✅ Yes
ScopeFunctionBlock{ }Block{ }
Use in modern code?❌ Avoid✅ When value changes✅ Default choice

🏆 The Professional Rule (Memorize This)

Useconstby default. Switch toletonly when you know the value must change. Never usevar.

script.js
Run Online
const siteName = "MyBlog";
// Never changes → const
let visitors = 0;
// Changes constantly → let
visitors = visitors + 1;

This habit makes your code safer and instantly marks you as someone who writesmodernJavaScript.

Understanding Scope: Where Variables Live 🏠

Scopeanswers the question:"Where in my code can I access this variable?"This is wherevarandlet/consttruly part ways.

Block Scope (let & const)

letandconstonly existinside the nearest{ }block:

script.js
Run Online
if (true) {
  let message = "I exist only inside these braces";
  console.log(message);
  // ✅ Works
}console.log(message);
// ❌ ReferenceError: message is not defined

Function Scope (var)

varignores blocksand only respects functions — it leaks out:

script.js
Run Online
if (true) {
  var leaked = "I escaped the block! 👻";
}console.log(leaked);
// "I escaped the block! 👻" — surprising and bug-prone

This "leaking" behavior is exactly why the JavaScript community abandonedvar. Block scope matches how developersthinkcode should work.


Variable Naming Rules (And Best Practices)

❗ Hard Rules — Break These and JavaScript Errors Out

  1. Names can containletters, digits,_and$
  2. Namescannot start with a digit
  3. Names arecase-sensitive(scoreandScoreare different variables)
  4. Reserved keywordsare banned (let,const,if,function,return…)
script.js
Run Online
let userName;
// ✅
let _count;
// ✅
let $price;
// ✅
let 1stPlace;
// ❌ Error — starts with a digit
let user-name;
// ❌ Error — hyphens not allowed
let let;
// ❌ Error — reserved keyword

⭐ Best Practices — These Make You Look Like a Pro

  1. Use camelCase:firstName,totalScore,isLoggedIn— the universal JavaScript convention
  2. Be descriptive:let studentScorebeatslet s— code is read far more than it's written
  3. Booleans start with is/has/can:isOnline,hasPermission— reads like a question
  4. Constants in SCREAMING_CASE(optional style for fixed config values):const MAX_USERS = 100;

How JavaScript Stores Values (Simple Version) 🧠

When you create a variable, JavaScript asks for a piece of your computer's memory and keeps a note:"the labeluserNamepoints to this spot."

Two behaviors worth knowing early:

Primitive Values Are Copied

script.js
Run Online
let a = 10;
let b = a;
// b gets a COPY of 10
b = 99;
console.log(a);
// 10 — a is untouched ✅

Numbers, strings, and booleans areprimitives— assigning them copies the actual value.

Objects and Arrays Are Referenced

script.js
Run Online
let cart1 =["shoes"];
let cart2 = cart1;
// cart2 points to the SAME list
cart2.push("watch");
console.log(cart1);
// ["shoes", "watch"] — both changed! 😮

Arrays and objects are stored byreference— both variables point to one shared box. You don't need to master this yet (there's a full lesson on data types coming in this series), but file it away — this behavior surprises every beginner eventually.

Common Beginner Mistakes (And Fixes)

❌ Mistake🔍 What Happens✅ Fix
Using a variable before declaring itReferenceErrorAlways declare withlet/constfirst
let score; let score = 5;SyntaxError: already declaredDeclare once; then just usescore = 5;
Changing aconstTypeErrorUseletif the value must change
let 1name = "x"Syntax errorNames can't start with digits →let name1
TypinguserNameasusernameReferenceErrorJavaScript is case-sensitive — copy-paste names
Still usingvareverywhereWeird scope bugsDefault toconst, useletwhen needed

Quick Self-Check: Lesson 4 Quiz 🧠

  1. Which keyword should be yourdefaultchoice:var,let, orconst?
  2. What's the output?let x; console.log(x);
  3. Can you re-declare aletvariable in the same scope?
  4. What's the output?
    script.js
    Run Online
    const nums =[1, 2];
    nums.push(3);
    console.log(nums);
  5. True or false:letvariables can be accessed anywhere, even outside their{ }block.

(Answers: 1. const — switch to let only when re-assignment is needed · 2. undefined · 3. No — JavaScript throws a SyntaxError · 4. [1, 2, 3] — const blocks re-assignment, not content changes · 5. False — let is block-scoped)


JavaScript Decision Matrix & Syntax Comparison

Understanding the mechanical differences between variable declarations and execution environments is critical for writing performant, bug-free modern JavaScript.

Variable Declarations: var vs let vs const
Feature / Propertyvar (Legacy ES5)let (Modern ES6+)const (Modern ES6+)
ScopeFunction ScopeBlock Scope ({})Block Scope ({})
Hoisting BehaviorHoisted (initialized as undefined)Hoisted (Temporal Dead Zone - ReferenceError)Hoisted (Temporal Dead Zone - ReferenceError)
Reassignable✓ Yes✓ Yes✗ No (Immutable binding)
Redeclarable in Same Scope✓ Yes (Error-prone)✗ No (SyntaxError)✗ No (SyntaxError)
Window Object BindingCreates property on windowDoes not attach to windowDoes not attach to window
Environment Decision Matrix: Browser Client-Side vs Node.js Server-Side
DimensionClient-Side (Web Browser)Server-Side (Node.js / Deno)
Global Objectwindow, document, navigatorglobal, process, globalThis
DOM & UI Manipulation✓ Full access (document.querySelector)✗ No DOM (Headless / Non-UI)
File System & OS Access✗ Blocked (Sandboxed security)✓ Full access (fs, os, child_process)
Primary FocusInteractive UI, animations, client stateREST APIs, microservices, databases, I/O streaming

Runnable JavaScript Code Example & Practical Implementation

script.js
Run Online
// 1) var Keyword (Function Scoped & Hoisted)
function varDemo() {
  console.log(hoistedVar);
  // undefined (hoisted)
  var hoistedVar = "Initialized now";
  if (true) {
    var leaked = "Leaks outside if-block";
  } console.log(leaked);
  // "Leaks outside if-block"
}varDemo();
// 2) let Keyword (Block Scoped & TDZ)
function letDemo() {
  let score = 50;
  if (true) {
    let blockOnly = "Trapped in block";
    console.log(blockOnly);
  } score = 75;
  // Re-assignment allowed
  console.log("Score:", score);
}letDemo();
// 3) const Keyword (Immutable Binding & Object Mutation)
const user = {
  name: "Alice", role: "Developer"
};
user.role = "Lead Architect";
// Allowed! Mutating heap property
console.log("Updated User:", user);
const frozenUser = Object.freeze( {
  name: "Bob", role: "Manager"
});
// frozenUser.role = "Director"; // Fails silently or throws TypeError in strict mode
// 4) Value Storage (Stack vs Heap)
let primitive1 = 100;
let primitive2 = primitive1;
// Copy by value on Stack
primitive2 = 200;
console.log("primitive1:", primitive1);
// 100
let heapObj1 = {
  title: "Original"
};
let heapObj2 = heapObj1;
// Copy pointer reference
heapObj2.title = "Mutated";
console.log("heapObj1.title:", heapObj1.title);
// "Mutated" (Both point to same heap memory)

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked questions for frontend & full-stack roles
Q

Q1: What is the Temporal Dead Zone (TDZ) for let/const?

A: TDZ is the time window between entering a block scope and reaching the variable's declaration line. Accessing the variable in TDZ throws a ReferenceError.
Q

Q2: Why can you modify properties of a const object, but cannot reassign the object itself?

A: const locks the 64-bit pointer address stored on the call stack. Properties live in heap memory; modifying properties alters heap memory contents without changing the stack pointer address.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations