Working with Variables: var
, let
, const
In JavaScript, variables are containers for storing data values. There are three ways to declare variables in JavaScript: var
, let
, and const
. Each has different scoping rules and behaviors. In this tutorial, we'll explore the differences between them and how to use them properly.
1. var
var
is the original way to declare variables in JavaScript. Variables declared with var
are function-scoped, meaning they are available within the function in which they are declared. If declared outside of a function, they are globally scoped.
// Example of var:
function testVar() {
var x = 10;
if (true) {
var x = 20; // same variable
console.log(x); // 20
}
console.log(x); // 20
}
testVar();
In the example above, notice how the value of x
changes inside the block and affects the outer scope. This can sometimes lead to bugs, which is why let
and const
were introduced.
2. let
let
was introduced in ES6 and provides block-scoping. This means that a variable declared inside a block (within curly braces) is only available within that block.
// Example of let:
function testLet() {
let y = 10;
if (true) {
let y = 20; // different variable
console.log(y); // 20
}
console.log(y); // 10
}
testLet();
In this example, the let
variable y
inside the block does not affect the outer variable y
. This provides more predictable behavior and helps avoid some of the pitfalls of var
.
3. const
The const
keyword is used to declare variables that are constant and cannot be reassigned. Just like let
, const
is also block-scoped. While the value of a const
variable cannot be changed, if the value is an object or array, you can still modify its properties or elements.
// Example of const:
const z = 30;
z = 40; // Error: Assignment to constant variable
const arr = [1, 2, 3];
arr.push(4); // This is allowed
console.log(arr); // [1, 2, 3, 4]
While const
prevents re-assignment, it does not make objects or arrays immutable. In the example above, you can still modify the contents of an array declared with const
.
Best Practices
- Use
let
for variables that you expect to reassign within a block or scope. - Use
const
for variables that should not be reassigned. - Avoid using
var
, as it can introduce unexpected bugs due to function-scoping.
Conclusion
Understanding the differences between var
, let
, and const
is essential for writing clean, predictable JavaScript code. While var
is still valid, using let
and const
helps avoid common pitfalls and improves code readability and maintainability.