JS Variables
A variable is a named container for a value. Modern JavaScript has three keywords for declaring them — but you only need two: let and const.
The three keywords
| Keyword | Scope | Can reassign? | When to use |
|---|---|---|---|
const | Block | No | Default. Use whenever the binding won't change. |
let | Block | Yes | When the variable's value needs to change (loop counter, mutable state). |
var | Function | Yes | Legacy. Avoid in new code — has confusing hoisting + scope rules. |
Examples
JS
const PI = 3.14159; // constant — never reassigned let count = 0; // can change count = count + 1; const items = [1, 2, 3]; // const means the binding is fixed items.push(4); // the array contents can still change // items = []; // ← this would throw
Naming rules
- Start with a letter,
_or$(not a digit). - Case-sensitive:
totalandTotalare different. - Use
camelCasefor variables and functions — that's the JS convention. - Use
UPPER_CASEfor genuine constants known at compile time. - Reserved words (e.g.
class,return,typeof) can't be names.
Tip: Default to
const. Only switch to let when you actually need to reassign. Never reach for var in new code.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
let name = "World";
const greeting = "Hello, " + name + "!";
document.getElementById("out").textContent = greeting;
</script>
</body>
</html>
Try it Yourself »
Exercise
Declare a value that will not change.
PI = 3.14159;
The default modern choice for non-reassigned bindings.
Discussion
Loading…