Variables: The Memory of Your App

Variables: The Memory of Your App in JavaScript: Think of a variable as a Storage Box with a label.

Concept Explanation

Think of a variable as a Storage Box with a label. In the early days (before 2015), we only had one type of box: var. It was a "leaky" box that sometimes caused bugs because it could be seen from outside the room it was in.

Modern JavaScript (ES6) introduced two better boxes:

  1. let: For values that will change (like a user's score in a game).
  2. const: For values that never change (like your API key or the speed of light).

Syntax or Core Structure

The Temporal Dead Zone (TDZ)

Unlike var, which is "hoisted" (moved to the top) and initialized as undefined, let and const exist in the TDZ. If you try to use them before they are declared, the app will crash instantly. This is a good thing because it prevents many hidden bugs.

// 1. Reassignable
let score = 10;
score = 20; // Allowed

// 2. Fixed
const pi = 3.14159;
// pi = 4; // Error! Assignment to constant variable.

// 3. Scoping
{
    let local = "Hidden";
}
// console.log(local); // Error! local is not defined outside the {}

Common Mistakes

  1. Using var in 2026: Never use var. It doesn't respect block scope {}, which leads to confusing bugs in loops.
  2. Naming Confusion: Don't use generic names like x or data. Use descriptive names like totalInvoiceAmount.
  3. Global Pollution: Declaring variables without let or const makes them "Global." This is like leaving your trash in the middle of the street for everyone else to trip over.

Best Practices

  • Const by Default: Always start with const. Only change it to let if you are certain you need to reassign the value. This makes your code "Immunable" and safer.
  • CamelCase: Use isLoggedIn or userProfileData. JavaScript is case-sensitive!
  • Group your declarations: Keep your variables at the top of your functions or files for better readability.

Practice Exercises

  1. The Constants Challenge: Try to reassign a const variable and observe the error in the console.
  2. The Scope Explorer: Create a let variable inside a for loop and try to print it outside the loop.
  3. The Namer: Write a list of 5 variables needed for a "Recipe" app and give them professional CamelCase names.