Scope in JavaScript is not a very complicated concept, but it is also not easy to grasp. Welcome to part 2 of my scope series. If you haven't followed part 1, here is the link for you to read. Scope in JavaScript - Part 1.
In the
previous section we talked about limit of scope and when the function is
executed, a new memory area is created. So, in this part, let's go through the
new sections.
Table of
contents:
· Variable access scope of a function.
· How a variable is accessed.
· When a called variable is cleared from
memory
Let's go to
see the content!
Variable access scope of a function.
As we said
earlier, a function is like a solid stronghold. What exists inside the function
has a higher tier than what is outside of it. Let's look at the example to
understand more!
// The lowest tier
function stronghold() {
// higher tier
function strongholdx2() {
// higher higher tier
function strongholdx3() {
// higher higher higher tier
function strongholdx4() {
// ........
}
}
}
}
There is a
law that your country makes. Areas with a higher rank will be able to use their
own resources and regions with a lower rank. But the parent stronghold cannot
use the resources that the children stronghold has. The deeper the strongholds
are inside the strongholds, the higher rank they are.
let property = 'The global property'
function stronghold() {
let gold = 'The property is gold'
console.log(`I have ${property} is ${gold}`)
// => I have The global property is The property is gold
console.log(`I have ${property} is ${diamond}`)
// => Uncaught ReferenceError: diamond is not defined
function strongholdx2() {
let diamond = 'The property is
diamond'
console.log(`I have ${property} is ${diamond}`)
// => I have The global property is The
property is diamond
}
strongholdx2()
}
stronghold()
console.log(`I have ${property} is ${gold}`)
// => Uncaught ReferenceError: gold is not
defined
console.log(`I have ${property} is ${diamond}`)
// => Uncaught ReferenceError: diamond is
not defined
It means
that a function can access a variable on its own and outside of its container.
Same with parent functions can't take variables inside children function.
How to access a variable
Variables,
also known as treasures in your country, are stored in chests (let/const name).
When used, chests will find out who is allowed to use it, where to put
treasures in the chests and what areas can use it.
Let's recall
the concept of the previous section. Regions with a higher rank will be allowed
to use their own resources and regions with a lower rank.
This means
that when a variable is called in a deeper scope, if it can't find the variable
in the scope itself, it will run outside the parent scope to look for the
variable. Until it comes out to global. If there is no such variable outside of
global, it will give an error.
Let's look
at the two examples below to see how to access variables.
Example 1:
let scope = 'scope'
{
{
{
{
{
console.log('We are learning ' + scope)
//
=> We are learning scope
}
}
}
}
}
Example 2:
{
{
{
{
{
console.log('We are learning ' + scope)
//
=> Uncaught ReferenceError: scope is not defined
}
}
}
}
}
You will see
how to use variables inside. When the variable is excute, it will immediately
observe in its environment, if there is no declared variable, it will jump out
to search until it finds the variable.
Let's make
an example to see, how well you understand the scope.
let scope = 'scope'
{
let scope = 'scope1'
{
let scope = 'scope2'
{
let scope = 'scope3'
{
console.log('We are learning ' + scope)
// => We are
learning scope3
}
}
}
}
If you
guessed the result would be “We are learning scope3” then you already have a
correct answer. If it's not true, that's okay, let's look at reason.
The variable
when executed will jump to the nearest scope containing it, if that scope has
an initialized variable, it will be assigned to that variable. It will ignore
more distant variables and only give preference to the most recently
initialized variables.
Let's see
another example:
The result will be:
let scope = 'scope'
{
let scope = 'scope1'
{
let scope = 'scope2'
{
let scope = 'scope3'
{
console.log('We are learning ' + scope)
// => What is will
be logged ?
let scope
}
}
}
}
I can
explain a little, the variable let(const) is created will be put into the “Temporal
death zone” and temporarily not accessed. And calling the variable will give
priority to getting the value in the nearest region. In this case, right at
that scope, there is a let scope variable, but it has not been assigned. And
such use will give an error.
When a called variable is cleared from memory
Variables
located at the global location will be deleted when your program or website is
terminated or refreshed.
As I
mentioned in the previous section, the function being executed will create its
own memory area for that function. Every time the function ends, the variable
in the function, along with that function, will be deleted from memory. In
contrast, variables set to global always exist until the program or website
terminates or refreshes.
This means
that you minimize the initialization of variables at global to avoid
duplication that can cause unexpected bugs. And also to reduce the load on your
system memory when dealing with unused resources.
Inheriting
the above, the variable in the scope will be deleted when the scope ends.
For a more special case, let's look at the example below:
function createCounter() {
let count = 0
function increaseCount() {
return count++
}
return increaseCount
}
let counter = createCounter()
console.log(counter()) // => 0
console.log(counter()) // => 1
console.log(counter()) // => 2
console.log(counter()) // => 3
Amazing! At
the end of the function, the variable has not been deleted. You think the
theory is wrong. Not really, this is the theory of closure that will be covered
in future articles.
The summary
is that the function createCounter() is referenced by the variable counter. A
variable within a referenced function will not be deleted when the function
terminates. Only lost when the program or website ends or refreshes.
Conclusion
We have just
gone through part 2 of scope, you already know the knowledge about variable
access scope of a function, how a variable is accessed, when a called variable
is cleared from memory
Thank you for joining with me. Have a good day!
0 Nhận xét