JavaScript Variables: var, let, and const
Master variable declaration in modern JavaScript. Understand scoping differences between var, let, and const.
Declaring Variables
A variable is a container for storing data values. In modern JavaScript (ES6+), there are three ways to declare a variable.
1. The const Keyword
Variables defined with const cannot be Reassigned. They are block-scoped. Best Practice: Always use const unless you know the value needs to change.
const pi = 3.14159;
pi = 3; // Throws TypeError: Assignment to constant variable.2. The let Keyword
Variables defined with let can be updated but not re-declared within the same scope. They are also block-scoped.
let age = 25;
age = 26; // This is perfectly fine3. The var Keyword (Legacy)
The var keyword was the original way to declare variables. It is function-scoped (or globally scoped) and allows re-declaration. It is generally recommended to avoid var in modern development due to unpredictable hoisting behavior.
var name = "John";
var name = "Doe"; // Allows re-declaration without errors