What is Scope?
Scope in JavaScript is the area where we have valid access to variables or functions. JavaScript has three types of Scopes. Global Scope, Function Scope, and Block Scope(ES6).
- Global Scope - variables or functions declared in the global namespace are in the global scope and therefore is accessible everywhere in our code.
//global namespacevar g = 'global';function globalFunc() {function innerFunc() {console.log(g); // can access "g" because "g" is a global variable}innerFunc();}
- Function Scope - variables,functions and parameters declared within a function are accessible inside that function but not outside of it.
function myFavoriteFunc(a) {if (true) {var b = 'Hello ' + a;}return b;}myFavoriteFunc('World');console.log(a); // Throws a ReferenceError "a" is not definedconsole.log(b); // does not continue here
- Block Scope - variables (let,const) declared within a block can only be access within it.
function testBlock() {if (true) {let z = 5;}return z;}testBlock(); // Throws a ReferenceError "z" is not defined
Scope is also a set of rules for finding variables. If a variable does not exist in the current scope it look ups and searches for a variable in the outer scope and if does not exist again it looks up again until it reaches the global scope if the variable exists then we can use it if not it throws an error. It searches for the nearest variable and it stops searching or looking up once it finds it. This is called Scope Chain.
/* Scope ChainInside inner function perspectiveinner's scope -> outer's scope -> global's scope*///Global Scopevar variable1 = 'Comrades';var variable2 = 'Sayonara';function outer() {//outer's scopevar variable1 = 'World';function inner() {//inner's scopevar variable2 = 'Hello';console.log(variable2 + ' ' + variable1);}inner();}outer();// logs Hello World// because (variable2 = "Hello") and (variable1 = "World") are the nearest// variables inside inner's scope.
October 23, 2022
1415
Read more
What is the JavaScript += Operator and How Do You Use It?
December 04, 2022
JavaScriptUsing the startsWith() Method in JavaScript
December 04, 2022
JavaScriptReverse a String in JavaScript: 2 Easy Methods
December 02, 2022
JavaScript