Animations
API
Arrays
Async
Basics
Challenges
Classes
Console
Dates
Debugging
DOM Elements
DOM Methods
DOM Properties
Event Listeners
Flow Control
Forms
Functions
Global Functions
JSON
Keywords
Libraries (3rd party)
Math
Modules
Objects
Snippets
String
Types
Widgets
Window Object
ES2015 introduced two important new JavaScript keywords: let
and const
.
Variables defined with const behave like let variables, except they cannot be reassigned.
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, we cannot change constant primitive values,
but we can change the properties of constant objects.
If an object, you can change it's contents!
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
// 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";
let resistanceMsg = "I will resist!";
const borgMsg = "Resistance is futile!";
try
{
// This will create an error
borgMsg = resistanceMsg;
}
catch (error)
{
alert("you cant reassign a const - dummy!");
console.error(error);
}
let demo1 = document.getElementById("demo1");
demo1.innerHTML = borgMsg;