JavaScript Variables and Constants are fundamental to any script. They are used to store data values that can be retrieved and manipulated later. This post will explore how to declare and use variables and constants in JavaScript with practical examples.
What Are JavaScript Variables and How to Declare Them?
In JavaScript, variables are like containers that hold information. You can declare a variable using one of three keywords: var, let, or const. Let’s look at each one:
Using var
The var keyword is the oldest way to declare a variable. It has a function scope, meaning it’s accessible anywhere within the function where it’s defined.
var name = 'John Doe';
console.log(name); // Output: John Doe
var name = 'Jane Doe'; // Re-declare the same variable
console.log(name); // Output: Jane DoeNote: Re-declaring variables with var can lead to unexpected behavior, especially in large scripts, since the variable can be unintentionally overwritten.
Using let
The let keyword is a newer and better way to declare variables. It has block scope, meaning it’s only accessible within the block (e.g., within curly braces) where it’s defined.
let age = 25;
console.log(age); // Output: 25
age = 26; // Update the variable
console.log(age); // Output: 26
// let age = 30; // Error: You cannot re-declare a variable with let in the same scopeUsing const
The const keyword is used to declare a constant, meaning the value cannot be reassigned after it’s set. Like let, it also has block scope.
const birthYear = 1995;
console.log(birthYear); // Output: 1995
// birthYear = 2000; // Error: You cannot reassign a constantNote: If the value assigned to a const is an object or array, its properties can still be changed:
const person = { name: 'John' };
person.name = 'Jane'; // Works - modifying a property, not reassigning
console.log(person.name); // Output: Jane
// person = { name: 'Bob' }; // Error - reassigning the variable itselfTip for Beginners: Always use
constunless you know the value will change. It helps prevent accidental changes and makes your code easier to understand.
Understanding Variable Scope
Scope determines where you can access your variables in your code. Let’s break it down:
- Global Scope: Variables declared outside any function can be used anywhere in your code.
- Function Scope: Variables declared with
varinside a function are only available within that function. - Block Scope: Variables declared with
letorconstare only available within the block they’re defined in.
var globalVar = 'I am global';
function testVar() {
var functionVar = 'I am a function variable';
console.log(globalVar); // Accessible
console.log(functionVar); // Accessible
}
if (true) {
let blockVar = 'I am a block variable';
console.log(blockVar); // Accessible inside the block
}
testVar();
// console.log(functionVar); // Error: functionVar is not defined outside the function
// console.log(blockVar); // Error: blockVar is not defined outside the blockIn the above example, globalVar is accessible globally, functionVar is accessible only within the testVar function, and blockVar is accessible only within the block where it is declared.
Hoisting and the Temporal Dead Zone
Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during the compile phase. However, only the declarations are hoisted – not the initializations.
The way hoisting works differs between var, let, and const:
// var is hoisted and initialized as undefined
console.log(a); // undefined (no error)
var a = 10;
// let and const are hoisted but NOT initialized
// Accessing them before declaration throws a ReferenceError
console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 20;The period between entering a block scope and the line where let or const is declared is called the Temporal Dead Zone (TDZ). During this time, the variable exists but cannot be accessed:
{
// TDZ starts here for 'x'
// console.log(x); // ReferenceError
let x = 42; // TDZ ends - 'x' is now initialized
console.log(x); // 42
}The var Pitfall in Loops
A common and confusing bug with var occurs in loops, because var does not create a new scope for each iteration:
// Problem with var
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Output: 3, 3, 3 (not 0, 1, 2!)
// Solution with let
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 100);
}
// Output: 0, 1, 2 (correct!)With var, there is only one i variable shared across all iterations. By the time the setTimeout callbacks execute, the loop has finished and i is 3. With let, each iteration gets its own scoped copy of j, preserving the correct value.
Key Differences Between var, let, and const
The following table compares the behavior of JavaScript’s var, let, and const by key properties such as scope, re-declaration, and re-assignment:
| Property | var | let | const |
|---|---|---|---|
| Scope | Function-scoped | Block-scoped | Block-scoped |
| Re-declaration | Allowed | Not allowed | Not allowed |
| Re-assignment | Allowed | Allowed | Not allowed |
| Hoisting | Yes, initialized with undefined | Yes, but in TDZ until declared | Yes, but in TDZ until declared |
| Initialization | Optional | Optional | Required |
| Use in loops | Not suited for loops due to scope issues | Best suited for loops | Works in loops but value cannot be reassigned |
Rules for Naming JavaScript Variables
Naming variables in JavaScript follows specific rules to ensure clarity and avoid errors:
- Begin with a Letter, Underscore, or Dollar Sign: Variable names must start with a letter, an underscore (_), or a dollar sign ($).
- Case-Sensitive: Variable names are case-sensitive, meaning
nameandNameare different variables. - No Reserved Keywords: Variable names cannot be reserved keywords like
var,function, orclass. - Use CamelCase for Multi-word Names: Use camelCase for variable names that consist of multiple words.
let firstName = 'John'; // camelCase
let _private = 'secret'; // starts with underscore
let $price = 20; // starts with dollar sign
// let var = 'value'; // Error: reserved keywordBest Practices
Here are some best practices when using variables and constants in JavaScript:
- Use
constby default. It ensures your variables cannot be reassigned, leading to fewer bugs and a more predictable codebase. - Use
letfor values that change – such as loop counters, accumulator values, or conditional state. - Avoid
varin modern code. Its function-scoped behavior and hoisting quirks can lead to unexpected bugs. - Declare variables at the top of their scope. This makes the code easier to read and avoids TDZ-related confusion.
- Use descriptive names. Choose clear, meaningful variable names like
userAgerather thanxortemp.
FAQs
Common questions about JavaScript variables and constants:
Conclusion
Variables and constants are fundamental to programming in JavaScript. Understanding the differences between var, let, and const, as well as their scope and hoisting behavior, is crucial for writing clean and efficient code.
For a deeper dive into common errors and how to prevent them, check out the post on How to Avoid Common Mistakes with JavaScript Variables. For more JavaScript fundamentals, explore the guides on strings, operators, and functions.

