const is used to declare one or more constants, which must be initialized when declaring, and the value cannot be modified after initialization.
Const-defined constants are similar to variables defined using let:
There are two differences between the two:
const definition constants also have block-level scope
var a = 10; const x = 'world'; if (a > 0){ const x = 'hello'; console.log(x); // Output x here as hello } console.log(x); // The output x here is world
and cannot have the same name as other variables or functions in its scope
{ var x = 'world'; const x = 'hello'; // Error report}
Constants declared by const must be initialized, but variables declared by let do not need to be initialized
// Wrong writing method const PI; PI = 3.14
The following is the correct way to write, assign value at the same time of declaration
// Correct way to write const PI = 3.14;
the value cannot be modified after initialization
const PI = 3.14; PI = PI + 1; // The error reported
. Strings and numeric types defined using const are immutable. When an object or array is defined, the contents inside can be modified.
const defines the object to modify the properties
const person = { name: "yoyo", age: 20, }; person.name = 'hello'; person.age = 30; console.log(person.name); // hello console.log(person.age); //age
but cannot reassign the object
const person = { name: "yoyo", age: 20, }; person = {name: 'xx', age: 23}; // Error reported
const Define an array to modify the value of a member
const a = ['hello', 'world']; //Modify element a[0] = "yoyo"; console.log(a); // ['yoyo', 'world'] a.shift('12'); console.log(a); // ['world'] a.unshift('xx'); console.log(a); // ['xx', 'world'] a.push('yy'); console.log(a); // ['xx', 'world', 'yy']
also cannot reassign constant arrays:
const a = ['hello', 'world']; a = ['x', 'y']; // Error
summary: A constant is a quantity whose value (memory address) cannot be changed. For common definitions of const, an initial value is required.