Variable in Javascript
const
const declares a block-scoped variable with a constant reference.
- Scope: Block Scope. A const variable is only accessible within the block ({ ... }) in which it is defined.
- Reassignment: Not allowed. A const variable cannot be reassigned a new value after its initial assignment. This will throw a TypeError.
- Initialization: Mandatory. A const variable must be initialized at the time of its declaration. Failure to do so results in a SyntaxError.
- Hoisting: const variables are hoisted to the top of their block but are not initialized. They are in a "Temporal Dead Zone" (TDZ) from the start of the block until the declaration is encountered. Accessing a const variable before its declaration results in a ReferenceError.
- Mutability: const only ensures the variable's reference is immutable, not the value it points to. If a const variable holds an object or an array, the properties or elements of that object/array can be modified.
Example:
// Block Scope
if (true) {
const PI = 3.14159;
}
// console.log(PI); // ReferenceError: PI is not defined
// Reassignment
const GREETING = "Hello";
// GREETING = "Hi"; // TypeError: Assignment to constant variable.
// Mutability
const CONFIG = { port: 8080 };
CONFIG.port = 3000; // This is allowed. CONFIG still points to the same object.
// Temporal Dead Zone
// console.log(MY_CONST); // ReferenceError: Cannot access 'MY_CONST' before initialization
const MY_CONST = 100;
let
let declares a block-scoped variable that can be reassigned.
- Scope: Block Scope. A let variable is only accessible within the block ({ ... }) in which it is defined.
- Reassignment: Allowed. The value of a let variable can be updated or reassigned within its scope.
- Initialization: Optional. A let variable can be declared without being initialized. If not initialized, it defaults to the value undefined.
- Hoisting: let variables are hoisted to the top of their block but are not initialized. They are in the Temporal Dead Zone (TDZ) until their declaration is encountered. Accessing a let variable before its declaration results in a ReferenceError.