JavaScript Variables and Data Storage: Beginner Guide to var, let, and const

JavaScript Variables and Data Storage: Beginner Guide to var, let, and const

How to Declare, Name, and Store Data in Modern JavaScript Without Coercion Bugs

Author
Nguyen Bao Huy
16:33:00 08/02/2026
4 min read
0 comments
Quick Answer:
Variables in JavaScript are named containers used to store data values. Modern JavaScript uses const by default for values that never change and let for values you intend to reassign. Avoid using the legacy var keyword and never create undeclared variables automatically. Identifiers are case-sensitive, and mixing strings with numbers during addition triggers automatic type concatenation.

1. What Is a Variable? (Containers for Data)

Think of a variable as a labeled storage box inside your computer's memory. When you assign a value to a variable, you place an item into that box so you can retrieve or update it later in your program.

JavaScript provides 4 ways to declare a variable:

  1. Automatically (Undeclared) — Never use this in real projects.
  2. Using var — Legacy syntax (1995–2015).
  3. Using let — Modern syntax for reassignable values.
  4. Using const — Modern syntax for permanent values.
javascript
// 1. Automatic declaration (Anti-pattern: creates accidental global variables)
x = 5;
y = 6;
total = x + y; // 11

// 2. Legacy declaration (Avoid in modern apps)
var legacyScore = 100;

// 3. Modern reassignable variable
let currentScore = 100;
currentScore = 120; // Valid

// 4. Modern constant variable
const maximumPlayers = 4;
// maximumPlayers = 5; // Throws TypeError: Assignment to constant variable

Practical Rule of Thumb:

  • Default to const for every variable, object, and array you create.
  • Switch to let only when you know the value must change (such as counters in loops or running totals).
  • Never use var unless maintaining an ancient legacy codebase without modern build tools.

2. The Assignment Operator (=) vs. Algebra

In mathematics, the equal sign (=) denotes equivalence ($x = y$). In JavaScript, the single equal sign is the assignment operator. It evaluates whatever is on the right side and assigns the resulting value to the variable on the left side:

javascript
let score = 10;

// In algebra this equation is impossible; in JavaScript it increments the variable:
score = score + 5; 
console.log(score); // 15

The computer first computes score + 5 (which equals 15), then places that new value back into the score storage container.

3. Declaring vs. Initializing: The undefined State

Creating a variable name is called declaring it. Giving it a starting value is called initializing it:

javascript
// Declared without an initial value:
let customerEmail;
console.log(customerEmail); // undefined

// Initialized later when data is available:
customerEmail = "support@stackra-agency.com";
console.log(customerEmail); // "support@stackra-agency.com"

Declaring Multiple Variables in One Statement

You can declare several variables in a single statement by separating them with commas:

javascript
// Single-line declaration:
let user = "John Doe", role = "Admin", active = true;

// Multi-line declaration (Cleaner and easier to read):
let productName = "Ergonomic Desk",
    productPrice = 299,
    inStock = true;

4. Variable Naming Rules (Identifiers)

Variable names are called identifiers. JavaScript enforces specific naming constraints that every developer must follow:

  • Allowed Characters: Names can contain letters, numbers, underscores (_), and dollar signs ($).
  • Start Character: Names must begin with a letter, $, or _. They cannot start with a number:
javascript
let 100days = "Invalid"; // SyntaxError: Invalid or unexpected token
let days100 = "Valid";   // Valid

Case Sensitivity: Identifiers are strictly case-sensitive. lastName and lastname are treated as two distinct storage containers:

javascript
let itemCode = "A1";
let ItemCode = "B2";
console.log(itemCode); // "A1"
console.log(ItemCode); // "B2"
  • No Reserved Keywords: You cannot use JavaScript keywords (such as let, class, return, or function) as variable names.

Special Identifiers: The Dollar Sign ($) and Underscore (_)

JavaScript treats $ and _ just like regular letters:

javascript
// Dollar sign conventions (often used as library aliases or UI element references)
let $submitButton = document.getElementById("submit");
let $price = 99;

// Underscore conventions (commonly used by developers to flag private or internal data)
let _internalId = "usr_9481";
let _cache = null;

5. Variable Re-declaration: Why let and const Prevent Bugs

One of the biggest flaws with legacy var is that it allows accidental re-declaration without raising any errors, silently overwriting existing variables:

javascript
// With legacy var:
var carModel = "Tesla";
var carModel; // No error! Variable retains "Tesla"

var carModel = "Volvo"; // Silently overwrites the original value
console.log(carModel); // "Volvo"

Modern JavaScript solves this hazard. Re-declaring a variable defined with let or const within the same scope immediately triggers an explicit error:

javascript
let accountId = "ACC-001";
let accountId = "ACC-002"; 
// SyntaxError: Identifier 'accountId' has already been declared

6. Arithmetic vs. String Concatenation Quirks

JavaScript handles arithmetic dynamically based on data types. The plus operator (+) serves a dual role: it performs mathematical addition for numbers and text concatenation for strings.

When you mix numbers and strings with +, JavaScript converts the numbers into strings:

javascript
// Case A: Pure mathematical addition
let mathResult = 5 + 2 + 3;
console.log(mathResult); // 10

// Case B: String concatenation
let fullName = "John" + " " + "Doe";
console.log(fullName); // "John Doe"

// Case C: Leading string forces subsequent numbers into strings
let stringFirst = "5" + 2 + 3;
console.log(stringFirst); // "523" (Not 10!)

// Case D: Left-to-right evaluation handles math first, then concatenates
let numberFirst = 2 + 3 + "5";
console.log(numberFirst); // "55" (2 + 3 = 5, then 5 + "5" = "55")

Quick Comparison: var vs. let vs. const

Featurevar (Legacy)let (Modern)const (Modern)
ScopeFunction scopeBlock scope {}Block scope {}
Reassignable?YesYesNo
Can Re-declare?Yes (Dangerous)No (Protected)No (Protected)
Default ValueundefinedundefinedMust initialize upon declaration
Best Use CaseAvoid in new codeCounters, dynamic statesDefault choice for all variables

Summary Checklist

  • Always declare variables explicitly using const or let.
  • Use const by default; only switch to let when the stored value must be reassigned.
  • Remember that variable names are case-sensitive and cannot begin with digits.
  • Beware of string concatenation when adding numbers with the + operator.
1 engineers appreciated this

First Lesson

You are at the beginning of this curriculum.

Latest Tutorial

More chapters coming soon to this topic.

Author avatar

Nguyen Bao Huy

Lead Fullstack & AI Solutions Engineer

Specializing in Next.js App Router, React 19, TypeScript, and modern design systems. Passionate about creating seamless user experiences.

Discussion

0

No comments yet

Be the first to share your thoughts, question a concept, or provide additional tips!

Leave a Reply

Share your insights, questions, or solutions with the developer community.

Your avatar
0 / 500 characters