A Global scope, a Functional or a block?
A peek into the hidden hero of Javascript: Scopes.
A let variable defined inside a function can't be called outside it yet, a var variable declared at the top happens to be a welcome guest to every function or block of code? Huh, I wonder why?
Guessed the reason?
Okay, Hint: It's there in the title.
Don't know about it? Are you sure about that? What if I tell you that you know it already, you just didn't see it before.
It's what is called as Scope of a variable. Consider it as a VIP pass, having three levels of access:
Global - Is welcome everywhere
Functional - Can function within it's area of reach
Block - The smallest kid on the block who plays in his little world
So right off the bat, what exactly is a scope?
Scope :
The scope is all about the visibility of your variables. It tells us where they can be called and also do the job of preventing unintentional modifications.
A variable defined in a higher-level scope can be used within nested scopes.
Pretty neat right? So a global scope variable can be called and redeclared inside a function scope or a block scope. But not the other way around.
Perplexed? Let us visualize it to get a better understanding.
Functional Scope
Here, the let keyword acts within the constraints of the function and can further be used in any "block" of code, like a for loop, if condition, etc. And thus it is a functional scope.
Block Scope
Whereas here, the let keyword blockScope is restricted to the block of code and cannot be called in the parent function code. Hence, it is block scoped.
Global Scope
If you've understood the above two definitions, tell me this :
What would you call a variable defined at the beginning of your code which can be called within any function or scope? drum rolls
A Globally Scoped Variable! Bingo!
So to sum it up, Any globally scoped variable can become functionally scoped and block-scoped but not vice versa. Hope this made Scope a little less intimidating to you all, and as for my scope of writing more blogs, let me know in the comments below. Cause, after all
There's always scope for Improvement. Until next time folks!