JavaScript Variables

let, const and var.

✍️ 3 exercises + code challenge in this lesson

Variables are containers for storing data. JavaScript has three keywords to declare them:

  • const: the value cannot be reassigned. Use it by default.
  • let: the value can change later.
  • var: the old way (before 2015). It has confusing scope rules; avoid it in new code.

Both let and const are block-scoped: they only exist inside the { } block where they are declared.

A const object or array can still have its contents changed; only the variable itself cannot point to something else.

Key Takeaways: JavaScript Variables

Mastering JavaScript Variables helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Variables Code Example

JavaScript
<pre id="out"></pre>
<script>
const log = (...a) => document.getElementById("out").textContent += a.join(" ") + "\n";
const city = "Lahore";
let visitors = 100;
visitors = visitors + 50;

const skills = ["HTML", "CSS"];
skills.push("JavaScript"); // allowed: changing contents

log(city, "has", visitors, "visitors");
log("Skills:", skills.join(", "));

try {
  city = "Karachi";
} catch (e) {
  log("Error:", e.message);
}
</script>
Free sign-in required · Google login available

JavaScript Variables Practice Exercises

Check what you learned in “JavaScript Variables”.

/ 3 solved
Fill in the blank

Declare a constant that cannot be reassigned.

 PI = 3.14;
✓ Correct! Not quite. Try again.
Multiple choice

Which keyword should you avoid in modern JavaScript?

✓ Correct! Not quite. Try again.
Code challenge

Declare a variable city with the value "Lahore" and log it.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services