JavaScript — Scope
Today I want to talk about Scope
in JavaScript
Scope
: “Determines the accessibility of variables, objects, and functions from different parts of the code”
So what does that mean?
Before we talk about what a Scope
is let’s talk about block
.
A block
is a group of statements.
For example
function helloWorld {
console.log("Hello World!");
}
if (i === 1) {
console.log("true");
]
for (let i = 0; i < 10; i++) {
console.log("Hello World!");
}
Everything inside { }
is considered a block.
So if we have a function
function helloWorld();
let hello = "Hello World!";
return hello;
}
how do I print this?
helloWorld(); //just executes the function doesn't print anything
console.log(helloWorld()); //prints "Hello World!"
then how about
console.log(hello);
this will result in
error: hello is not defined
Why is that?
It’s because the code cannot access the variable hello
from inside the function.
There are a few different type of Scopes
.
Block Scope
simply, declared inside a variable, cannot be used outside
//x cannot be used here
{
let x = 3
//x can be used here
}
//x cannot be used here
2. Function Scope
similar to a Block Scope
, but declared inside a function, can only be used in a function
//x cannot be used here
function haveNumber {
let x = 3;
//x can be used here
}
//x cannot be used here
3. Global Scope
variable declared outside a block, can be used anywhere in the code
let x = 3; //x can be used here
function haveNumber {
return x;
//x can be used here
}
console.log(x); //x can be used here
Scope Pollution
Once a variable
is declared globally, it takes whats called a global namespace
. namespace
is the range which a variable
can be used. namespace
is the same as scope
, but the term is used when we talk about variable names.
Let’s look at an example,
Good Scoping
Then we need to get in habit to write code with good scoping practices.
What do we need to do to keep it clean?
Best way is to not globally declare variables. Sometimes it’s inevitable but however it’s best to keep the variables inside blocks.
Not only does a tightly scoped code increase the quality of the code, it also increases the readability. It also increases the maintainability.
Let’s get in a good habit together!