The const keyword and constant declarations
Basic Concepts of the const Keyword
const is a variable declaration keyword introduced in ECMAScript 6, used to create block-scoped constants. Unlike var
and let
, variables declared with const
must be initialized at the time of declaration and cannot be reassigned. This characteristic makes const
an ideal choice for declaring values in a program that should not change.
const PI = 3.14159;
console.log(PI); // 3.14159
PI = 3.14; // TypeError: Assignment to constant variable
Block Scope Feature of const
const
, like let
, has block scope, meaning that a constant declared with const
is only valid within the code block where it is declared. This contrasts sharply with the function scope of var
.
{
const localConst = "Only valid inside the block";
console.log(localConst); // "Only valid inside the block"
}
console.log(localConst); // ReferenceError: localConst is not defined
const with Objects and Arrays
Although variables declared with const
cannot be reassigned, the properties or elements of composite types like objects and arrays can still be modified. This is because const
ensures that the memory address bound to the variable remains unchanged, not the data at that address.
const person = {
name: "Alice"
};
person.name = "Bob"; // Allowed to modify properties
console.log(person.name); // "Bob"
person = {}; // TypeError: Assignment to constant variable
const numbers = [1, 2, 3];
numbers.push(4); // Allowed to modify the array
console.log(numbers); // [1, 2, 3, 4]
const and the Temporal Dead Zone
const
, like let
, is subject to the Temporal Dead Zone (TDZ) phenomenon. Accessing a const
variable before its declaration will throw a ReferenceError
, which differs from the variable hoisting behavior of var
.
console.log(a); // ReferenceError: Cannot access 'a' before initialization
const a = 10;
Best Practices for const
In practical development, const
should be the default way to declare variables, with let
used only when reassignment is truly necessary. This approach improves code readability and maintainability.
- Use
const
for primitive constant values. - Use
const
for objects and arrays that won't be reassigned. - Use uppercase letters and underscores to name true constants (e.g., configuration values).
const MAX_ITEMS = 100;
const API_URL = "https://api.example.com";
const DEFAULT_CONFIG = {
timeout: 5000,
retry: 3
};
const in Loops
In for...of
and for...in
loops, const
can be used to declare loop variables, with a new binding created for each iteration.
const arr = [1, 2, 3];
for (const item of arr) {
console.log(item); // 1, 2, 3
}
const obj = {a: 1, b: 2};
for (const key in obj) {
console.log(key); // "a", "b"
}
const and Module Imports
In the ES6 module system, import
statements behave similarly to const
declarations, meaning imported bindings cannot be reassigned.
// module.js
export const name = "Module";
// main.js
import { name } from './module.js';
console.log(name); // "Module"
name = "New Name"; // TypeError: Assignment to constant variable
const and Object Freezing
To create truly immutable objects, const
can be combined with the Object.freeze()
method. This prevents adding, deleting, or modifying object properties.
const frozenObj = Object.freeze({
prop: "value"
});
frozenObj.prop = "new value"; // Fails silently or throws TypeError (in strict mode)
console.log(frozenObj.prop); // "value"
const and Global Objects
Variables declared with const
in the global scope do not become properties of the window
object, unlike var
.
var globalVar = "I'm global";
const globalConst = "I'm also global";
console.log(window.globalVar); // "I'm global"
console.log(window.globalConst); // undefined
Performance Considerations for const
From a performance perspective, using const
may offer slight optimization opportunities. JavaScript engines can make more assumptions about const
variables, potentially generating more efficient code. While such optimizations are usually negligible, they are an additional benefit of using const
.
const in TypeScript
In TypeScript, const
retains its ES6 features but also has special type inference behavior. Literal types declared with const
are inferred as the narrowest possible type.
const str = "hello"; // Type is "hello", not string
const num = 42; // Type is 42, not number
Browser Compatibility for const
Modern browsers generally support the const
keyword, but older browsers may require transpilation tools like Babel. Feature detection can be used to confirm const
availability.
try {
const test = true;
console.log("const is supported");
} catch (e) {
console.log("const is not supported");
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:let关键字及其块级作用域
下一篇:暂时性死区(TDZ)概念