Wayjsconstant.md - brainchildservices/curriculum GitHub Wiki
Slide 1
When to use JavaScript const?
As a general rule, always declare a variables with const unless you know that the value will change.
Always use const when you declare:
- A new Array
- A new Object
- A new Function
- A new RegExp
Slide 2
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.
Because of this you can NOT:
- Reassign a constant value
- Reassign a constant array
- Reassign a constant object
But you CAN:
- Change a constant array
- Change a constant object
Slide 3
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] = "Toyota";
// You can add an element:
cars.push("Audi");
Slide 3 DownWards
But you can NOT reassign the array:
Example
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; // ERROR
Slide 4
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:"white"};
// You can change a property:
car.color = "red";
// You can add a property:
car.owner = "Johnson";
But you can NOT reassign the object:
const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR