JavaScript - Constants

原创
admin 4个月前 (08-06) 阅读数 18 #JavaScript

JavaScript - Constants

JavaScript constants are immutable variables that maintain their value throughout program execution. Unlike regular variables, constants cannot be reassigned or redeclared once initialized.

Declaring Constants with const

The const keyword was introduced in ES6 alongside let to create block-scoped constants. A constant must be initialized during declaration:

const PI = 3.14159; // Valid declaration
const MAX_SIZE; // SyntaxError: Missing initializer

Key Characteristics of Constants

Constants in JavaScript have several important behaviors:

  • Block-scoped like let variables
  • Cannot be redeclared in same scope
  • Must be initialized during declaration
  • No hoisting - cannot be used before declaration

Working with Objects and Arrays

While the reference to a const object/array cannot change, their contents can be modified:

const colors = ['red', 'green'];
colors.push('blue'); // Valid
colors = []; // TypeError: Assignment to constant

When to Use Constants

Constants are ideal for:

  • Mathematical constants (PI, GRAVITY)
  • Configuration values
  • Any value that shouldn't change during execution

Comparison with var and let

Feature var let const
Scope Function Block Block
Reassignment Allowed Allowed Prohibited
Redeclaration Allowed Prohibited Prohibited

Using const helps prevent accidental reassignments and makes code intentions clearer. For values that need to change, use let instead.

版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权本站发表,未经许可,不得转载。

作者文章
热门
最新文章
标签列表