Code Example: |
const is used for variables that should not be reassigned. It creates a constant reference, meaning that the variable itself cannot be changed (though the contents of objects or arrays assigned to const can still be modified).
const name = 'Alice';
// name = 'Bob'; // Error: Assignment to constant variable
let is used for variables that may be reassigned, but it has block-scoping (unlike var, which is function-scoped). This makes it easier to reason about where variables are accessible. Example:
let count = 0;
if (true) {
let count = 1; // This is a different variable than the one outside
console.log(count); // 1
}
console.log(count); // 0
By using const and let, you can avoid common issues with var, such as unexpected hoisting and re-declarations, leading to cleaner and more maintainable code.
|