Lesson

JS Variables

10 min reading
Free Course

JavaScript Variables: Storing Values with const, let, and var

JavaScript 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.

Comparing 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

Practical Variable Declaration Example

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)}`);

Why Modern JavaScript Avoids var

Variables 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.

Common Mistakes to Avoid

  • Creating accidental globals: Assigning total = 10 without let or const attaches total to the global window object in sloppy mode. Always enable strict mode or ES modules.
  • Using let everywhere: Using let for fixed values makes readers scan the whole file to see if the variable changes. Default to const.
  • Expecting const to freeze arrays or objects: const locks the variable binding, not the contents inside an object or array.

Frequently Asked Questions

Should I always start with 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.

Can I declare multiple variables in one statement?

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.

What value does an uninitialized let variable hold?

Writing let status; without = sets its initial value to undefined until you assign a real value.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
JavaScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum