iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

KeywordScopeCan reassign?When to use
constBlockNoDefault. Use whenever the binding won't change.
letBlockYesWhen the variable's value needs to change (loop counter, mutable state).
varFunctionYesLegacy. 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: total and Total are different.
  • Use camelCase for variables and functions — that's the JS convention.
  • Use UPPER_CASE for 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;

Test yourself

Q1. Which keyword should be your default choice?
Q2. Which is block-scoped AND reassignable?
Q3. `const items = [];` followed by `items.push(1);` is…

Discussion

Loading…