About Lesson
var, let, const
JavaScript allows you to declare variables using three keywords: var, let, and const.
1. var:
- It’s function-scoped, meaning the variable is accessible throughout the function in which it’s declared.
- Variables declared with var can be re-declared and updated.
Example:
JavaScript
var age = 25;
var age = 30; // Re-declaration is allowed
age = 35; // Update is allowed
2. let:
- Introduced in ES6, it’s block-scoped, meaning the variable is only accessible within the block ({}) in which it is declared.
- Variables declared with let can be updated but cannot be re-declared within the same block.
Example:
JavaScript
let age = 25;
age = 30; // Update is allowed
3. const:
- Also block-scoped like let, but once a value is assigned to a const variable, it cannot be reassigned. It must be initialized at the time of declaration.
Example:
JavaScript
const age = 25;
// age = 30; // This will throw an error