How to Use JavaScript variables?
Constants
const is similar to let with the only difference being that we
cannot change the value the constants points to. We should use const
to define values and functions that we have no intention of
mutating. This, of course, means that we must initialize a const
immediately with a value since we cannot bind it to another value
later on.
const constants are block scoped, which means that they are valid
within the scope they are defined in.
Mutation
We cannot modify the value a constant is bound to. The code in the example below will give us an error telling us that we can't assign to a constant.
const age = 23 // initialized to 100age = 24 // invalid assignment to const
const essentially creates immutable bindings, which means that we
cannot change what value the constant is bound to. But it is important
to remember that, in JavaScript, complex data types (arrays, functions
and objects) are passed by reference. So we can modify properties of
these complex data types while keeping the original reference. The
code below will work without errors.
const person = {name: "Hadrian",occupation: "Warrior"}console.log(person.name) // "Hadrian"person.name = "Royce" // mutates objectconsole.log(person.name) // "Royce"
When we initialize person with a complex data type (object) we bind
the constant to the reference of this new object. We can mutate the
internals of the object without causing an error.
person = {} // Error
The code above will not work however, since it tries to bind the constant to a value with a completely different reference.
Initialization
Constants must be initialized with a value.
const counter = 99console.log(counter) // 99
In the above example we declare a constant counter and initialize it
with a value.
const counter // SyntaxError
This example will result in a syntax error telling us we are missing
= in the constant declaration.
Scope
let and const behaves the same way when it comes to scope as they
are both block scoped.
const env = 'prod' // globally scoped// new scope{const country = "Norway" // country is created hereconsole.log(country) // "Norway"// new nested scope{const capital = "Oslo" // capital is created hereconsole.log(country, capital) // "Norway Oslo"} // capital is destroyed hereconsole.log(env) // "prod"console.log(capital) // ReferenceError} // country is destroyed here
Test yourself
Description
Define a new const constant with the identifier
planet
and initialize it with the value
Tellus
Tests
- 1
You should use a
constconstant declaration. - 2
You should give the constant
planetthe string valueTellus.