JavaScript ConstES6 introduced the const keyword, which is used to define a new variable in JavaScript. Generally, the var keyword is used to declare a JavaScript variable. Const is another keyword to declare a variable when you do not want to change the value of that variable for the whole program. The difference is just that var is for normal variable declaration whose value can be changed, whereas a variable value declared using const keyword cannot be changed. Const variable declaration/initializationFollowing is the syntax or simple code for const variable declaration and initialization. Copy Code Test it NowOutput It will display the value of the const variable x without any error. The value of const variable x = 16 Now, we will discuss some properties of the variables defined using const. PropertiesFollowing are the properties of const variable:
ExamplesHere, we have some examples for different properties explanation practically. Example 1: With the help of this example, you will see that the const variable cannot be reassigned. Copy Code Test it NowOutput It will generate a type error because it is not possible to reassign the value to a constant variable. JavaScript error: Uncaught TypeError: Assignment to constant variable. on line 3 Example 2: In this example, you will learn that the const variable contains Block scope. Copy Code Test it NowOutput There will be no error by executing the above code. It will just print the value of x of different blocks without any syntax or type error. Block2: x = 23 Block3: x = 74 Block4: x = 49 Block1: x = 16 Example 3: This example will describe that the const variable cannot be hoisted. Copy Code Test it NowOutput It will generate a syntax error because redeclaration of a variable is not allowed. JavaScript error: Uncaught SyntaxError: Missing initializer in const declaration on line 4 Example 4: This example will show you that the const variable cannot be initialized after declaration. Copy Code Output It will generate a syntax error because initialization is not allowed after the declaration of const variable. JavaScript error: Uncaught SyntaxError: Missing initializer in const declaration on line 2 Example 5: In JavaScript, const allows you to only modify the value of the array, but the reference to the array cannot be changed. Copy Code Output Here, you can see the Manya name has been replaced by Krishna. Although the array was declared using const keyword. So, it will display all values of the array without any error both times. Aparna, Manya, Amayra, Jahanvi Aparna, Krishna, Amayra, Jahanvi Example 6: In this example, we will show you that the const variable value cannot be changed or modified. Copy Code Output Here, you can see that you cannot reinitialize the object values by the same name, but the object values can be changed by using their reference. [object object] [object object] |