First of all, this story is based on Stephen Curtis -33 Fundamentals Every Javascript Developer Should Know and you can read it here.
I thought it is great concepts to know although it is not a requirement. So i decided to learn and explain these concepts one by one.
#6. Global scope & Local scope
Scope determines the accessibility of variables and there’s 2 kind of type, global scope and local scope. Variables declared in global scope can be accessed globally no matter where they are, whereas variables declared in local scope can only be accessed locally.
const global = ‘global’; // global scopefunction doSomething() {
console.log(global);
}doSomething();console.log(global);
In this example, variable global
can be accessed from inside and outside of the function since it was declared in global scope. Simply think it can be seen from anywhere.
function doSomething() {
const local = ‘local’; // local scope console.log(local);
}doSomething();console.log(local);
However, unlike global scope, variable local
is declared in local scope and can only be accessed inside of the function. Simply think that curly braces block any third party who is trying to see inside of curly braces.
This is called function scope. There’s basically two kinds of scope in local scope, function scope and block scope.
Function Scope
This scope is limited to the function itself and its children — other functions declared within this function.
function createMyName() {
const myName = ‘dongho’;
// only accessible in this function
}console.log(myName);
Variables declared in a function can not be accessed from the outside.
Block Scope
A block scope is similar to a function scope, but is limited to a block instead of a function.
if (true) {
const local = ‘local’; //local scope
}console.log(local);
For example, if we declare variable local
inside of if statement, we can not read local
from outside since it is declared in the local scope.
Block Scope with var
if (true) {
var local = ‘local’;
}console.log(local); --> local
What if we use var
in block scope instead of const
or let
. It works!!
This is one of the reason why using var
is not recommended. Since they ignore block scope, they might result in weird bugs in the future.
Conclusion
If there’ no local scope, we have to think about new variable name whenever we declare variables. But thanks to local scope, we don’t need to waste our time. Keep in mind, variables declared inside of blocks or functions can not be seen from outside. There’s a lot more we can learn about scope, but i think this simple concept is enough for practical use. Thanks for reading.