JavaScript Variables: var, let, and const
Explained
In JavaScript, variables are used to store data values. There are three main ways to declare variables:
1. var – Function-scoped, older way
- Can be re-declared and updated.
- Function scoped, not block scoped.
- Gets hoisted (moved to the top of its scope), but not initialized.
Example:
var message =
"Hello";
console.log(message); // Output: Hello
var message =
"Hi again";
console.log(message); // Output: Hi again
2. let – Block-scoped, modern way
- Can be updated but not re-declared in the same scope.
- Introduced in ES6 (ES2015).
- Recommended for reassignable values.
Example:
CopyEdit
let name =
"Alice";
console.log(name); // Output: Alice
name =
"Bob"; // allowed
console.log(name); // Output: Bob
// let name =
"Charlie"; Error: Identifier 'name' has already been
declared
3. const – Block-scoped, for constants
- Cannot be updated or re-declared.
- Must be initialized at the time of declaration.
- Best for constant values (like config values or fixed settings).
Example:
const PI = 3.14;
console.log(PI); // Output: 3.14
// PI = 3.14159; Error: Assignment to constant variable
// const PI = 3.14159; Error: Identifier 'PI' has already been
declared