Javascript Constant - const Keyword
JavaScript const
keyword is used to define constant values that can not changed once a value is set. The value of a constant can't be changed through reassignment, and it can't be redeclared.
The scope of const is block-scoped it means it can not be accessed from outside of block. In case of scope, it is much like variables defined using the let statement.
Constants 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.
JavaScript const
Keyword: Syntax
Below we have the syntax to define a constant value in JavaScript.
const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]]
We don't have to use var
or let
keyword while using the const
keyword. Also, we can define a list or a simple value or a string etc as a constant.
JavaScript const
Keyword Example
Lets understand, how to create constant in JavaScript program. See the below example:
{
const Pi = 3.14;
alert(Pi);
}
3.14
Let's try another example where we will try changing the value of the constant and see if we allowed to reassign value or not.
{
const Pi = 3.14;
alert(Pi);
// Reassign value
Pi = 3.143;
alert(Pi);
}
3.14
Uncaught TypeError: Assignment to constant variable.
JavaScript const
: Scope
The scope of the variable defined using const
keyword is same as that of a variable declared using the let
keyword. So, constant declared inside a block will not accessible outside of that block. Let's take an example and see:
{
const Pi = 3.14;
alert(Pi);
}
// outside block
alert(Pi); // error
3.14
Uncaught ReferenceError: Pi is not defined
JavaScript const
Keyword Usage Example
In the live example below we have added multiple code statements in which we have declared constant values and have given it different scope and have also tried to change the value of the constant.
To see the error, you can open the browsers developer tools(If you are using Chrome or Firefox browser), you will see the Uncaught TypeError: Assignment to constant variable error message in the console.
So this is how we can define a constant in JavaScript which can be used in cases where you want to define some constant values like domain name, any prefix value which is fixed, or any integer value, or may be a zipcode in your JavaScript code.
Also Read : - How to Build an Animated Counter with JavaScript