How to Use JavaScript variables?

Modern variables

let should be used to create all mutable variables in modern JavaScript code. We use let when we want to be able to assign another value to a variable. In all other cases a const should be used instead.

let variables are block scoped, which means that they are valid within the scope they are defined in and will not mutate a shadowed (variable with same name in parent scope) variable.

Mutation

We can modify the value of a let variable by assigning it a new value using the = symbol.

let counter = 100 // initialized to 100
counter = 99 // mutated to 99

Initialization

We can declare a let variable without immediately initializing it with a value. We have to be careful when doing this though, as we will get a runtime reference error if we use the variable before we have declared it.

let counter
counter = 99
console.log(counter) // 99

In the above example we declare a variable counter and use it only after we have given it a value.

console.log(counter) // ReferenceError
let counter = 99

In this example we try to use the variable counter in a function call without declaring it first. This results in an error.

Scope

let env = 'prod' // globally scoped
// new scope
{
let country = "Norway" // country is created here
console.log(country) // "Norway"
// new nested scope
{
let capital = "Oslo" // capital is created here
console.log(country, capital) // "Norway Oslo"
} // capital is destroyed here
country = "Sweden" // can mutate
console.log(country) // "Sweden"
console.log(env) // "prod"
console.log(capital) // ReferenceError
} // country is destroyed here

Test yourself

Description

Define a new let variable with the identifier

season

and initialize it with the value

winter

Tests

  1. 1 You should use a let variable declaration.
  2. 2 You should give the variable season the string value winter.
Editor