DEV Community

loading...

My Expedition With JavaScript: Interpretation of JS Scopes

siddhantjha profile image Siddhant Jha ・2 min read

Alt Text

Hello Dev World

I hope you all are keeping safe and getting adapted to the new normal. I am reinitiating my journey into the world of JavaScript after a break and I thought there is no better way to commit myself to this new endeavor than documenting my up’s and down’s with the most popular programming language out there.

Today, I tried to learn about “Scopes” in JavaScript. Here’s what I understood in most condensed form:

  • Scopes in JavaScript can be understood as

    “A set of rules that defines where you can access a particular value”.

  • Scopes can be divided into two categories:
    Global Scope
    Local Scope

  • Local Scope: Whenever you define a variable inside a function its scope gets limited to the function itself i.e. You can’t access that variable outside that function.

  • Global Scope: When a variable is declared outside any function and can be accessed by any function whatsoever. Then its scope can be considered as Global Scope.

  • Scopes are determined “Lexically”. It means that function can use a variable defined outside its code block only when the variable is declared beforehand.

  • Nested Functions creates a Scope Chain that ends at the Global Scope level.

Let’s See This In Action

Alt Text

In the example above, I have declared a variable “a” under the carnage of “Global Scope” and another variable “b” under the code block of the function named “add5” and the scope of the variable is “Local Scope”.

Alt Text

Due to the method of the declaration mentioned above “variable a” can be used whenever and wherever the user required independent of the code block while “variable b” can be used inside the function “add5” only.

That’s what I have learned today. I will try my best to keep this streak up and running all I need from you guys is support and motivation. Will catch up with you guys in the next post till then “Keep Learning, Keep Growing”.

Namaste
Siddhant Jha

Discussion

pic
Editor guide