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:
- let: For values that will change (like a user's score in a game).
- 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
- Using
varin 2026: Never usevar. It doesn't respect block scope{}, which leads to confusing bugs in loops. - Naming Confusion: Don't use generic names like
xordata. Use descriptive names liketotalInvoiceAmount. - Global Pollution: Declaring variables without
letorconstmakes 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 toletif you are certain you need to reassign the value. This makes your code "Immunable" and safer. - CamelCase: Use
isLoggedInoruserProfileData. JavaScript is case-sensitive! - Group your declarations: Keep your variables at the top of your functions or files for better readability.
Practice Exercises
- The Constants Challenge: Try to reassign a
constvariable and observe the error in the console. - The Scope Explorer: Create a
letvariable inside aforloop and try to print it outside the loop. - The Namer: Write a list of 5 variables needed for a "Recipe" app and give them professional CamelCase names.