A scope is like a place where we can access a certain declared variable in Javascript, when the variable is not availabe in a certain scope it cannot be used there.
Types of scopes
there are 3 main types of scopes found in Javascript
The global scope
This is the scope where you can access any declared variable or function and it is on the top level
const name = "John";
console.log(name); // John
the variable name is created in the global scope so it is accessible everywhere even inside a function scope
const name = "John";
function logName() {
console.log(name); //John
}
logName();
The function scope
This is the scope inside functions and methods and anything declared there cannot be accessed in the global scope
function createName() {
const name = "John";
console.log(name); // John
}
createName();
console.log(name); // name is not defined
The block scope (ES6 only)
This is the scope inside if statements and loops, any variable declared there with let and const cannot be accessed outside the scope
if (true) {
const name = "John";
}
console.log(name); // name is not defined
however, if we declare the variable with var, it can be accessed outside the scope
if (true) {
var name = "John";
}
console.log(name); // John
The scope chain
If we make a scope inside a scope inside another scope we make a scope chain
Example
function fnc1() {
//scope 2
return function () {
//scope 3
return function () {
//scope 4
return function () {
//scope 5
};
};
};
}
and every scope only has access to variables declared inside a higher level scope.
scope 5 has access to all scope 4, 3, 2 and global scope variables
scope 4 has access to all scope 3, 2, and global scope variables
etc
Top comments (0)