const, let, and varJavaScript variables are named containers that store data values in memory so your program can read and update them. Modern ES6+ code uses const by default, let when a value must be reassigned, and avoids legacy var.
const, let, and var| Keyword | Scope | Can Reassign? | Can Redeclare? | Modern Guidance |
|---|---|---|---|---|
const |
Block { } |
No | No | Default choice for almost everything |
let |
Block { } |
Yes | No | Use for counters, accumulators, state |
var |
Function | Yes | Yes | Avoid in modern code |
Choosing between const and let signals your intent clearly to anyone reading your code.
const storeName = "KoderShop"; // Never reassigned
let cartTotal = 0; // Updated as items are added
const items = [19.99, 12.5];
for (const price of items) {
cartTotal += price;
}
console.log(`${storeName} total: $${cartTotal.toFixed(2)}`);
varVariables created with var leak out of if blocks and for loops because var ignores curly-brace block boundaries. Also, var allows accidental redeclaration in the same scope and hoists as undefined, which hides bugs until runtime.
total = 10 without let or const attaches total to the global window object in sloppy mode. Always enable strict mode or ES modules.let everywhere: Using let for fixed values makes readers scan the whole file to see if the variable changes. Default to const.const to freeze arrays or objects: const locks the variable binding, not the contents inside an object or array.const?Yes, declare every variable with const first. Switch to let only when you intentionally need to reassign that variable later, such as inside a for loop or counter.
Yes, you can write let width = 10, height = 20;, though declaring one variable per line with const or let is clearer and produces cleaner Git diffs.
let variable hold?Writing let status; without = sets its initial value to undefined until you assign a real value.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.