In the above example we are defining variable a within our main call stack, which in turn becomes a global variable. This means a will be available within both first and second functions. In the first function we are defining a second variable called b with a value of 2. Because a was defined in the main call stack, it is also available to first, therefore the console.log will yield the results of both a and b. At this stage we define a function called second within first, which now has access to both a and b. In addition we define a third variable c and are able to view the results of all three once second is called from within first. Let’s look back at the call stack diagram and see how these variables are available within the different stages.
A major change we made from the last lesson was to embed second within first, instead defining it within the main call stack and invoking it within first. If second was defined within the main call stack, it would not have access to b.
As you can see from above, a will always be available within the main scope and any other blocks or functions (first and second) defined within it. The first function therefore has access to a and b and the second function has access to a, b, and c.
var, let and const
When defining variables, you have three main choices, var, let and const. Let’s take a look at these more closely. First of all const (which stands for constant) is a special type of variable that contains an immutable value. In other words, a value defined in a const variable cannot be reassigned or changed once it has been initialized. Take the following variable definition:
const homeCity = "New York"; homeCity = "Washington DC";
The code above would result in the following exception error: Uncaught TypeError: Assignment to constant variable.
- let (and const) will define a new binding within their local scope or block. In other words if you create a new block such as a conditional statement (wrapped in curly braces), the variable will only be available within that block.
- In contrast to this, var will only have a new scope if a new function is created. In other blocks, var is visible throughout the entire function or global scope.
To understand this better, take a look at the following example.
Image Credits: Photo by Bud Helisson on Unsplash.