JavaScript is a high-level, interpreted programming language primarily used for creating interactive and dynamic content on webpages. It was initially developed by Netscape Communications Corporation in collaboration with Sun Microsystems in 1995. JavaScript is now one of the core technologies of web development along with HTML and CSS.
Constants are useful for defining values that should remain constant throughout the execution of a program, such as mathematical constants, configuration values, or API keys.
In JavaScript, the `const` keyword is used to declare constants, which are variables whose values cannot be re-assigned or re-declared once initialized. Here's an overview of how it works:
1. Variable Declaration: We use `const` to declare a constant and assign an initial value to it. Once a constant is initialized, its value cannot be changed.
const PI = 3.14159; // Declaration and initialization
2. Block Scope: Constants declared with `const` have block scope, similar to variables declared with `let`. They are only accessible within the block in which they are declared, including any nested blocks.
if (true) {
const localVar = "Local constant";
console.log(localVar); // Accessible within the block
}
console.log(localVar); // Error: localVar is not defined (outside the block)
3. No Re-assignment: Once initialized, the value of a constant cannot be re-assigned. Attempting to re-assign a value to a constant will result in a TypeError.
const PI = 3.14159;
PI = 3.14; // TypeError: Assignment to constant variable
4. No Re-declaration: Constants declared with `const` cannot be re-declared within the same scope. Attempting to re-declare a constant with `const` in the same scope will result in a SyntaxError.
const PI = 3.14159;
const PI = 3.14; // SyntaxError: Identifier 'PI' has already been declared
5. Global Scope: Constants declared with `const` outside of any block are added to the global scope, similar to variables declared with `var` and `let`.
const GLOBAL_CONST = "Global constant";
6. Temporal Dead Zone (TDZ): Similar to variables declared with `let`, constants declared with `const` are also subject to the temporal dead zone. Attempting to access a constant before its declaration results in a ReferenceError.
console.log(PI); // ReferenceError: Cannot access 'PI' before initialization
const PI = 3.14159;