If you are learning JavaScript to build interactive web interfaces or server applications, understanding JavaScript variables is your most critical foundational milestone. Variables are the fundamental memory containers of every computer program—storing, tracking, and transforming data across your application’s lifecycle.
Modern JavaScript (ECMAScript 6 and beyond) provides three keywords to declare variables: const, let, and var. In this comprehensive beginner guide, we break down how variables work under the hood, how variable scope and hoisting operate, when to use each keyword, and the exact pitfalls to avoid in production code.
Table of Contents
- 1. What Is a Variable in JavaScript?
- 2. The Three Declaration Keywords: const, let, and var
- 3. Understanding Scope: Global, Function, and Block Scope
- 4. Hoisting and the Temporal Dead Zone (TDZ)
- 5. JavaScript Data Types: Primitives vs Reference Types
- 6. const with Objects and Arrays: Mutation vs Reassignment
- 7. Technical Comparison: const vs let vs var
- 8. Professional Naming Conventions & Best Practices
- 9. Common Variable Mistakes to Avoid
- 10. Frequently Asked Questions (FAQ)

1. What Is a Variable in JavaScript?
In computer programming, a variable is a named identifier bound to a specific location in computer memory that holds a value. That value can be text (strings), numbers, boolean flags (true/false), lists of items (arrays), or complex structured objects.
Whenever your application needs to remember information—such as an authenticated username, a shopping cart total, or whether a dropdown menu is open—it assigns that value to a variable.
userAge). The contents inside the box represent the variable’s value (e.g., 25). Whenever your program needs that number, it references the label. If you are new to coding logic, check out our guide on what is programming in simple words.2. The Three Declaration Keywords: const, let, and var

Keyword Comparison Matrix: The matrix details scope boundaries, reassignment rules, and re-declaration constraints. Modern best practice mandates defaulting to const for all variable declarations, utilizing let only when reassignment is explicitly required in loops or state machines, and completely avoiding legacy var.
JavaScript has evolved significantly since its inception in 1995. Prior to ES6 (2015), var was the only declaration mechanism. Today, professional JavaScript relies on const and let to write predictable, bug-free software.
1. const (Constant Reference)
Use const when the variable’s identifier should never be reassigned a new value during program execution:
const maxLoginAttempts = 5;
const apiBaseUrl = "https://api.codecrunch.me/v1";
// Attempting to reassign throws an error:
maxLoginAttempts = 10; // TypeError: Assignment to constant variable.2. let (Reassignable Variable)
Use let when you know the variable’s value must change as your code executes—such as loop iterators, accumulator sums, or UI state toggles:
let userScore = 0;
userScore += 10; // Allowed! userScore is now 10
userScore += 25; // userScore is now 353. var (Legacy — Avoid in Modern Code)
var is the legacy JavaScript variable keyword. It has function-level scope (rather than block scope) and allows accidental redeclaration, which frequently introduces subtle bugs in large applications:
var temperature = 20;
var temperature = 30; // Accidental redeclaration is silently permitted!const everywhere. Use let only when you know the value must change. Never use var.3. Understanding Scope: Global, Function, and Block Scope
Scope determines the visibility and accessibility of variables across different regions of your code. JavaScript has three primary scope levels:
1. Block Scope (const and let)
Any code wrapped in curly braces { ... } (such as if statements, for loops, or standalone blocks) creates an isolated block scope. Variables declared with const or let inside that block are completely invisible to the outside world:
if (true) {
const secretCode = "Alpha77";
let accessGranted = true;
}
console.log(secretCode); // ReferenceError: secretCode is not defined2. Function Scope
Variables declared inside a JavaScript function cannot be accessed from outside that function, regardless of whether you used const, let, or var.
3. Global Scope
Variables declared outside of any function or block reside in the global execution context. They are accessible anywhere in your codebase, but overuse can cause naming collisions and unpredictable state bugs.
4. Hoisting and the Temporal Dead Zone (TDZ)
During the compilation phase before code execution, JavaScript engines allocate memory space for variable declarations. This mechanism is known as hoisting.
However, var and let/const behave completely differently during hoisting:
- var is initialized with undefined: If you read a
varvariable before its declaration line, JavaScript returnsundefinedinstead of an error. - let and const enter the Temporal Dead Zone: While
letandconstare hoisted, they remain uninitialized. Accessing them before their declaration line throws a clearReferenceError: Cannot access variable before initialization.
console.log(legacyVar); // Outputs: undefined
var legacyVar = "Hello World";
console.log(modernLet); // Throws: ReferenceError!
let modernLet = "Hello World";Official specifications on hoisting mechanics are detailed in the MDN JavaScript Grammar and Types Guide.
5. JavaScript Data Types: Primitives vs Reference Types

Stack vs Heap Memory Model: Primitives (numbers, strings, booleans, null, undefined, symbol, bigint) are stored by value in fast call stack memory. In contrast, reference types (objects, arrays, functions) store only an address pointer on the stack, while their mutable payload resides in the dynamic memory heap.
Deep-Dive: Understanding Shallow vs Deep Copying in JavaScript
Because objects and arrays are reference types, copying a variable does not duplicate the underlying data in heap memory. Instead, it copies the memory reference address:
// Reference Assignment Trap
const originalUser = { name: "Alex", settings: { theme: "dark" } };
const userCopy = originalUser;
userCopy.name = "Morgan"; // Mutates originalUser.name as well!To avoid accidental mutations, modern JavaScript provides two copying techniques:
- Shallow Copy with Spread Syntax (
{ ...obj }): Duplicates the top-level properties into a new heap object, but nested objects remain linked references.const shallowCopy = { ...originalUser }; shallowCopy.settings.theme = "light"; // STILL mutates originalUser.settings.theme! - Deep Copy with
structuredClone(): The native web API standard that recursively clones all nested objects, arrays, and dates without retaining reference links to the original memory addresses.const deepCopy = structuredClone(originalUser); deepCopy.settings.theme = "blue"; // Completely isolated! originalUser remains unchanged.
For complete language specifications, see the official ECMAScript Language Specification (ECMA-262) and MDN JavaScript Data Structures.
JavaScript is a dynamically typed language, meaning you do not explicitly state data types when declaring variables. However, understanding the underlying types is vital:
Primitive Types (Passed by Value)
- String: Text enclosed in quotes:
const name = "Alex";or template literals`Hello, ${name}!`. - Number: Integers and floating-point decimals:
const price = 19.99;. - Boolean: Logical flags:
const isActive = true;. - Null: Intentional representation of an empty or nonexistent value:
let selectedUser = null;. - Undefined: A variable that has been declared but not assigned a value.
- Symbol & BigInt: Unique identifiers and arbitrarily large integers.
Reference Types (Passed by Reference)
- Array: Ordered list of elements:
const techStack = ["HTML", "CSS", "JavaScript"];. - Object: Key-value paired dictionary:
const developer = { name: "Jordan", role: "Frontend Engineer", experienceYears: 3 };
6. const with Objects and Arrays: Mutation vs Reassignment
A common point of confusion for beginners is that const prevents reassignment, but it does NOT make reference objects immutable.
When you declare an array or object with const, the memory reference to that container is locked. You cannot assign a new array or object to that variable, but you can freely mutate its internal properties or push new items:
const fruits = ["apple", "banana"];
// Allowed! Mutating the internal contents:
fruits.push("cherry");
console.log(fruits); // ["apple", "banana", "cherry"]
// Forbidden! Reassigning the identifier:
fruits = ["orange", "grape"]; // TypeError: Assignment to constant variable!Object.freeze(developer).7. Technical Comparison: const vs let vs var
| Feature | const | let | var (Legacy) |
|---|---|---|---|
| Scope | Block { } | Block { } | Function or Global |
| Reassignable? | No | Yes | Yes |
| Redeclarable? | No | No | Yes (Source of bugs) |
| Temporal Dead Zone? | Yes (Throws ReferenceError) | Yes (Throws ReferenceError) | No (Returns undefined) |
| Production Verdict | Default Choice | Use for changing values | Avoid completely |
8. Professional Naming Conventions & Best Practices
Writing clean code means adhering to industry-standard conventions:
- camelCase: Always use
lowerCamelCasefor variable names:userAccountBalance,isLoading,totalCartItems. - Descriptive Names: Avoid cryptic single-letter names like
xortemp. Prefer explicit self-documenting identifiers likecurrentTemperatureCelsius. - Boolean Prefixes: Prefix boolean flags with
is,has, orshould:isLoggedIn,hasPermission,shouldShowModal. - SCREAMING_SNAKE_CASE: Reserve uppercase with underscores exclusively for global application configuration constants:
const MAX_FILE_SIZE_BYTES = 5242880;.
9. Common Variable Mistakes to Avoid
- Accidental Global Variables: Omitting
constorlet(e.g., writingcount = 1;) silently creates a property on the globalwindowobject. Always enable"use strict";or use modern ES modules. - Reassigning const Primitives: Forgetting that numbers, strings, and booleans cannot be reassigned when declared with
const. - Block Scope Leaks: Expecting a variable declared inside an
ifblock to exist outside that block.
To see how JavaScript variables connect to interactive DOM components on a live page, follow our tutorial on how to build a simple website using HTML and CSS, or explore the full career roadmap in our guide to frontend developer skills for beginners. If you want to build server APIs that store variable data in databases, read our primer on backend basics explained simply.
10. Frequently Asked Questions (FAQ)
Why should I never use var in modern JavaScript?
var lacks block scoping, meaning it ignores curly braces in loops and conditionals. It also allows accidental redeclaration of the same variable name and hoists with undefined, which frequently leads to silent bugs that are notoriously difficult to track down.
Can I change an array declared with const?
Yes. You can push, pop, shift, and reorder elements inside the array. const only stops you from reassigning the variable to a completely different array.
Where should I start learning JavaScript for free?
Check out our curated guide on how to start coding at home for free for the best zero-cost interactive platforms and sandboxes.
