The Const Statement
Constants are block-scoped, much like variables defined using the let statement. The value of a constant can't be changed through reassignment, and it can't be redeclared.
Table Of Contents
The let statement declares a block scope local variable, optionally initializing it to a value.
Description
This declaration creates a constant whose scope can be either global or local to the block in which it is declared. Global constants do not become properties of the window object, unlike var variables. An initializer for a constant is required; that is, you must specify its value in the same statement in which it's declared (which makes sense, given that it can't be changed later).
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
All the considerations about the "temporal dead zone" apply to both let and const.
A constant cannot share its name with a function or a variable in the same scope.
Syntax
/**
* Paramaters
*
* nameN - The constant's name, which can be any legal identifier.
*
* valueN - The constant's value; this can be any legal expression, including a function expression.
*
*/
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]]; 2
3
4
5
6
7
8
9
Code
Examples
- Constants are defined once, and their values cannot be reasigned.
The Unchanging Const
const number = 42;
try {
number = 99;
} catch(err) {
console.log(err);
// expected output: TypeError: invalid assignment to const `number'
// Note - error messages will vary depending on browser
}
console.log(number);
// expected output: 42
2
3
4
5
6
7
8
9
10
11
12
const BIRTHDAY = 28;
console.log(BIRTHDAY)
2
3
4
Constant example : Throws error because we attempt to reassign its value
const BIRTHDAY = 28;
BIRTHDAY = 29;
console.log(BIRTHDAY)
2
3
4
5
Pushing a value to the constant
You can manipulate values within a constant, for instance objects and arrays. Because you atre not chaning the value.
const ageArray = [];
ageArray.push(33)
console.log(ageArray)
2
3
4
5
6
7