The main difference between const
against var
and let
variables is that its value cannot be changed after being assigned. The const
variable was introduced to JavaScript in the ES2015 version of the standard. Together with the let
variable, it was supposed to replace var
variables, since it provided more safety with less system resources.
In particular, for new variables the "hoisting" rule was cancelled, where the compiler automatically hoisted variables from all over the script to its upper part. On one hand, this allowed declaring variables regardless of their assignments, but, on the other hand, it created difficulties in reading the code in future.
Also, const
always requires a declaration, while var
variables could ignore this if their value was assigned.
Key characteristics of const variables
1. To declare a variable, you must write const
and specify its identifier.
const number;
2. It is forbidden to use specific JavaScript keywords for a variable name.
Wrong identifiers:
const for;
const switch;
3. The const
variable can store data primitives (bool, numbers, strings) and more complex types like Arrays and Objects.
const number;
const countries = ["France", "Italy", "Spain"];
4. As an identifier of a const
variable, you can use combinations of numbers, upper and lower case letters of the English alphabet and symbols "_" and "$".
Correct identifiers:
const numbers;
const NUMBERS;
const new_Numbers;
Wrong identifiers:
const 10numbers;
const numbers?;
5. The value of the const
variable must be specified immediately after the declaration. This can be done on the same line or on the next.
const example1;
example1 = "a";
const example2 = "b";
6. The value of a const
variable cannot be changed after assignment. But this doesn't apply to the values inside the assigned Arrays and Objects.
const countries = ["France", "Italy", "Spain"];
countries[2] = "Portugal";
7. const
variables always have block scope. Accordingly, regardless of context, they are available only within the curly braces of the code block where they were declared.
function Action1(){
let number = 100;
}
8. If you declare a const
variable in the body of the script, it will have a global scope.
const test1 = "success";
function Action1(){
const test2 = test1;
}
9. You can assign a const
variable value only after its declaration.
Wrong declaration:
number = 50;
const number;
10. Inside closed blocks of code, you can create const
variables with identifiers identical to those outside the blocks. If identifiers match, the existence of external variables with the same identifier will be ignored by code inside the block.
const words = "apple";
function Action1(){
const words = "pineapple";
}