How to Use JavaScript variables?

Scope

All programming languages have a concept of scope and variable lifetimes.

Scopes manage the availability of variables and is what allows us to write complex multi-thousand line programs that work without forcing developers to give truly unique identifiers to every single variable.

When we say

variable x is in scope

we mean that we have access to the variable x and can get its value.

In JavaScript new scopes are created by code blocks, functions and modules.

In the next couple of sections we are going to look at how the different variable and constant types deal with scope.

What is a block?

A block is simply a list of zero or more statements grouped inside curly brackets.

// this is a block
{
let name = "block"
name = block + " scoped"
}
// another block created by the if statement
if (true) {
console.log("this is another block")
}

Blocks can be nested as much as we want where inner scopes has access to variables in outer scopes. The outermost scope is called the global scope and all variables defined here are accessible anywhere in the same file/module.

const maxRadius = 20.0 // global scope
function abc(r) {
const pi = 3.14 // abc function scope
if (r > maxRadius) {
const result = pi * r * r // if statement scope
return result
}
return pi * r
}

Notice how we have defined the maxRadius constant in the outermost global scope, which means that we can refer to it from any other scope in the file as proven by the if statement's predicate.

Code example: function

const x = 3
// function that doubles the number given
// and returns the result back to the caller
function double(x) {
const result = x * 2 // result is created here
return result
} // result is destroyed here
// and cannot be accessed
const twenty = double(10) // 20
console.log(x) // x is still 3
console.log(result) // result is out of scope here
// and will cause a ReferenceError

In the code example above we have a constant x that has been initialized with the value 3. We then have a function double that has one parameter x. The x that the function refers to is not the same x as the constant we defined earlier. We define a temporary constant result inside the double function. The scope of this constant is limited to the function's scope, meaning nothing outside the function can refer to it.

Calling double will give us the correct result without mutating (modifying) the variable x in the parent scope.