JavaScript Variables
Variables store values so you can use and reuse them throughout your code. Instead of writing the same value in ten places, you store it once in a variable and reference it by name.
The three keywords: const, let, and var
JavaScript has three ways to declare a variable. Here is the short version of when to use each:
- Use
constby default. It signals that this value will not be reassigned. - Use
letwhen you need to reassign the variable later. - Avoid
varin new code. It has scoping quirks that cause hard-to-find bugs.
const
const declares a variable that cannot be reassigned after it is created.
const siteName = 'Dev Handbook';
console.log(siteName); // Dev Handbook
// This will throw an error:
siteName = 'Something else'; // TypeError: Assignment to constant variable
const does not mean the value is frozen. If you store an object or array in a const variable, you can still change the contents. What you cannot do is point the variable at a different object.
const user = { name: 'Anna', age: 28 };
// Changing a property is fine
user.age = 29;
console.log(user.age); // 29
// Reassigning the variable is not allowed
user = { name: 'Joe' }; // TypeError
Use const for anything that does not need to change: configuration values, DOM references, imported modules, and most function declarations.
let
let declares a variable that can be reassigned. Use it when the value will change over time.
let score = 0;
score = score + 10;
console.log(score); // 10
score += 5;
console.log(score); // 15
A practical example: a loop counter or a value that accumulates:
let total = 0;
const prices = [9.99, 14.99, 4.99];
for (const price of prices) {
total += price;
}
console.log(`Total: $${total.toFixed(2)}`); // Total: $29.97
var (legacy)
var is the original way to declare variables in JavaScript. It still works, but it has two behaviours that trip people up.
1. var is function-scoped, not block-scoped.
This means a var declared inside an if block leaks out of that block.
if (true) {
var message = 'Hello';
}
console.log(message); // Hello (this leaks out of the block)
With let, the same code behaves more predictably:
if (true) {
let message = 'Hello';
}
console.log(message); // ReferenceError: message is not defined
2. var is hoisted.
JavaScript moves var declarations to the top of their function before the code runs. This means you can reference a var variable before the line where you declared it, and you will get undefined instead of an error. This makes bugs harder to track down.
console.log(count); // undefined (not an error, but confusing)
var count = 5;
let and const are also hoisted technically, but they are not accessible before their declaration. You get a clear error instead of a silent undefined.
Stick with const and let. You will rarely have a reason to reach for var.
Scope
Scope controls where a variable is accessible.
Block scope means the variable only exists inside the {} block where it was declared. Both const and let are block-scoped.
{
const greeting = 'Hello';
console.log(greeting); // Hello
}
console.log(greeting); // ReferenceError: greeting is not defined
Function scope means the variable exists anywhere inside the function where it was declared. var is function-scoped.
function greet() {
var name = 'Anna';
console.log(name); // Anna
}
greet();
console.log(name); // ReferenceError (var is still scoped to the function)
Global scope means the variable is accessible everywhere. Avoid creating global variables by accident. If you declare a variable without any keyword, it becomes a global.
// Do not do this
username = 'Anna'; // Creates a global variable
Naming rules
Variable names in JavaScript must follow these rules:
- Must start with a letter, underscore (
_), or dollar sign ($). - Can contain letters, numbers, underscores, and dollar signs.
- Cannot be a reserved keyword like
let,const,return, orif. - Are case-sensitive:
scoreandScoreare different variables.
By convention, JavaScript uses camelCase for variable names:
const firstName = 'Anna';
const totalScore = 0;
const isLoggedIn = true;
Common mistakes
Using var when you mean let: Modern JavaScript code uses let for reassignable variables. Save yourself the scoping headaches and use let.
Trying to reassign a const: If you need to change the value later, declare it with let, not const.
const count = 0;
count++; // TypeError: use let instead
Accidentally creating global variables: Always use const or let. A missing keyword creates a global variable that can interfere with other code.
function setup() {
apiKey = '12345'; // No keyword: this is now global, which is almost never what you want
}
FAQ
When should I use const vs let?
Start with const. If you find yourself needing to reassign the variable (a counter, a loop variable, a flag that flips between true and false), switch to let. You will use const for the majority of your variables.
What is hoisting?
Hoisting is JavaScript’s behaviour of moving declarations to the top of their scope before code runs. var declarations are hoisted and initialised to undefined. const and let declarations are hoisted but not initialised, so accessing them before their declaration throws a ReferenceError. In practice, just declare your variables before you use them and hoisting will not cause you problems.
For more on how scope works inside functions, see the Functions page.