JavaScript: JavaScript Variables
Variables are boxes for storing data — you label each box with a name, then put data in, take data out, or swap it anytime.
1. What Are Variables
Imagine a row of labeled boxes: one called "name" holds "John," another called "age" holds 25. The contents can change, but the label stays the same — that's a variable.
In JS, you create variables using declaration keywords (var / let / const) and assign values with the equals sign:
<!-- Script tag -->
<script>
var name = "John";
let age = 25;
const PI = 3.14;
</script>
2. The Problems with var
var was the only way to declare variables before ES6. It has two headache-inducing behaviors:
- Function scope — a variable declared with
varinside aniforforblock is accessible outside, which is counterintuitive - Hoisting —
vardeclarations are "hoisted" to the top of their scope, but assignments are not. You can use a variable before its declaration (its value will beundefined) without errors, which leads to subtle bugs
These two behaviors make var a breeding ground for bugs. In modern JS, var has been largely replaced by let and const.
3. let — Block Scope, Recommended Default
let was introduced in ES6 (2015) and fixes both problems with var:
- Block scope — only accessible within
{}, cannot be accessed outside the block - No hoisting — using a variable before its declaration throws an error (temporal dead zone)
In daily development, use let for variables that need to be reassigned.
4. const — Constants, Cannot Be Reassigned
const also has block scope, but it must be assigned at declaration and cannot be reassigned afterward.
Note: const restricts "reassignment," not "mutation." If a const holds an object or array, you can modify object properties or array elements — you just can't point the variable to a different object.
Use const by default; switch to let when you need to reassign — this is the best practice.
5. Variable Naming Rules
- Must start with a letter, underscore
_, or dollar sign$ - Subsequent characters can be letters, digits, underscores, or dollar signs
- Cannot start with a digit
- Cannot use JS keywords (
var,let,function, etc.) - camelCase is recommended:
firstName,totalPrice
6. Declaring Multiple Variables
You can declare multiple variables at once, separated by commas:
<!-- Script tag -->
<script>
let a = 1, b = 2, c = 3;
</script>
However, for readability, one variable per line is preferred.
▶ Example: var Hoisting and Function Scope
▶ Try it Yourself▶ Example: let Block Scope
▶ Try it Yourself▶ Example: const Constants
▶ Try it Yourself▶ Example: var / let / const Comparison
▶ Try it Yourself❓ FAQ
let and const to declare variables, while var is the older style. Variables declared with let can be reassigned, variables declared with const cannot be reassigned, and var does not have block scope. For new code, prefer const first and use let when the value needs to change.undefined usually means the variable has been declared but not yet assigned a value, such as reading a right after let a;. A ReferenceError means you accessed a variable that was never declared, or accessed a let/const variable before its declaration (the temporal dead zone). Check the declaration location and spelling to locate the issue.`Hello, ${name}`, or explicitly convert with String(value) or value.toString(). To output to the page, it is common to use document.getElementById('app').textContent = name, which is safer than directly concatenating HTML.📖 Summary
- Variables are boxes for storing data, created with a declaration keyword + variable name + assignment
varhas function scope and hoisting issues — avoid it in modern JSlethas block scope and no hoisting — use it when reassignment is neededconsthas block scope and cannot be reassigned — must be assigned at declarationconstprevents reassignment, but object/array properties and elements can still be modified- Priority: const first, let second, avoid var
📝 Exercises
- Basic: Declare a constant
SITE_NAMEwith your name usingconst, and a variablevisitCountset to 0 usinglet, then display both values on the page. - Intermediate: Create a page with a button that simulates a "visit counter" — each click increments
visitCountby 1 and displays the current value. Notice howletallows reassignment whileconstdoesn't. - Challenge: Create a page with a
conststudent object{ name: "John", scores: [80, 90, 75] }. Then add a new score of 85, calculate the average, and change the name to "Jane" — all without reassigning the const, proving that object contents can be modified.