Scope: What does it exactly mean?
Sougandika L
Immediate Joiner ll Serving Notice Period ll Software Developer at People Tech Group private Ltd Il ANGULAR l TYPESCRIPT l KENDOUI l NGRX l REDUX l HTML l SCSS I CSS l BOOTSTRAP
Hello everyone,
This is Sougandika. Do you want to know what is scope? Be with me till the end and I am sure that this will get into your head very clearly.
Let's start. Where you can access a specific variable or function in a code is nothing but a scope.
For example
1 function x(){ 2 console.log(a); 3 } 4 var a=10; 5 a();
When I try to do console log then javascript engine tries to search inside local memory space which means inside the execution context of x. It is not available now as nowhere we initialize 'a' inside x. what will be the output ? Will it print undefined or not defined or something else. Let's see
output: > 10
Yes in this case output will be 10. This means somehow it is able to access 'a' which is outside x. If we try to make it little more complex. For example
6 function x(){ 7 y() 8 function y(){ 9 console.log(a); 10 } 11 } 12 var a=10; 13 x();
Now, what will be the output? Will it be undefined or null or 10 or something else.
output > 10
This means it can access 'a' which is inside a function, which is inside another function, which is in global scope.
For suppose, consider variable a is inside function x,
14 function x(){ 15 var a=10; 16 y(); 17 function y(){ 18 console.log(a); 19 } 20 } 21 x();
Now, what will be the output? Give it a guess.
output > 10
But if we try to access a outside the function, how does it works?
It means that when we try to access 'a' outside the function, it is showing an error as a is not defined.
Here in the example, what is the scope of variable a? It means where I can access the variable a. In another way, we can say like " Is a inside the scope of function y?" It means "Can we access a inside function y?"
This is all about scope. Hope you got what scope is. That's all in this article. See you in my next article.
Thank you for your valuable time,
Sougandika L