Constants are block-scoped, much like variables declared using the 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. The destructuring assignment syntax can also be used to declare variables.
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
An initializer for a constant is required. You must specify its value in the same declaration. (This makes sense, given that it can't be changed later.) The All the considerations about the temporal dead zone apply to both
A constant cannot share its name with a function or a variable in the same scope. Unlike
ExamplesBasic const usageConstants can be declared with uppercase or lowercase, but a common convention is to use all-uppercase letters.
Block scopingIt's important to note the nature of block scoping.
const needs to be initialized
const in objects and arrays
However, object keys are not protected, so the following statement is executed without problem.
You would need to use
The same applies to arrays. Assigning a new array to the variable throws an error "Assignment to constant variable".
Still, it's possible to push items into the array and thus mutate it.
Specifications
Browser compatibilityBCD tables only load in the browser See alsoWhich keyword is used in a variable declaration to make the variable a named constant?If you want to define a variable whose value cannot be changed, you can use the const keyword. This will create a constant.
Which key word is used to declare variables?The variable total is declared with the let keyword. This is a value that can be changed.
How do you declare a variable called a name?To declare a variable is to create the variable. In Matlab, you declare a variable by simply writing its name and assigning it a value. (e.g., 'jims_age = 21;'). In C, Java you declare a variable by writing its TYPE followed by its name and assigning it a value.
|