➢The const keyword was introduced in ES6 (2015).
➢Variables defined with const cannot be Redeclared.
➢Variables defined with const cannot be Reassigned.
➢Variables defined with const have Block Scope.
Cannot be Reassigned
➢A const variable cannot be reassigned:
EXAMPLE:
const pi =3.1415;
pi = 10;
pi = pi + 10;
Constant Objects and Arrays
➢The keyword const is a little misleading.
➢It does not define a constant value. It defines a constant reference to a value.
Constant Arrays
➢You can change the elements of a constant array:
EXAMPLE:
// You can create a constant array: const cars = ["Saab", "Volvo", "BMW"];
// You can change an element:
cars[0] = "Saab";
// You can add an element:
cars.push("Audi");
Constant Objects
➢You can change the properties of a constant object:
EXAMPLE:
// You can create a const object: const car = {type:"Fiat", model:"500", color"red"];
// You can change an element:
cars.color = "red"; // You can add an element:
cars.owner = "Joshik";
Block Scope
➢Declaring a variable with const is similar to let when it comes to Block Scope.
➢The x declared in the block, in this example, is not the same as the x declared outside the block:
EXAMPLE:
let x = 10; // Here x is 10
{ let x = 5; // Here x is 5
} // Here x is 10