Scope

What is scope and why do we need it?

Introduction

JavaScript has a concept called scope. This is not an easy thing to understand for those new to software development. It’s not an absolutely requirement in order to write code, but understanding scope will make your code more professional, reduce errors and help you make powerful programming design patterns with it.

Scope in JavaScript: Global Scope versus Function Local Scope

In the above example, we declaring two variables: globalVariable and functionVariable then we simulate a console.log() to output the types of each of variable. Notice one is string, and the other is undefined.

Lastly, we call the whatsInMyGlobalScope function, which evaluates the availability of those two variables inside the function scope.

In Our Global Scope:

  • globalVariable is defined (it’s a string) because it’s declared in the global scope (it would also be defined if it was in the function scope).
  • functionVariable is undefined because it is only declared in the function scope.

In Our Function Scope:

  • globalVariable is defined because it’s declared in the global scope, same as above. It’s not defined in the function scope, but it is available to the function scope.
  • functionVariable is defined in the function scope if it is only referenced in the function scope.

To Summarize:

So, the inner scope can access any variables/functions that are declared outside of their scope. In our case, the inner scope is the function scope, and the outer scope is the global scope (there is no other higher level).

Scope is important in JavaScript because it can help us to reduce side effects in our code, essentially these are unexpected behaviors, outputs, etc…It also gives us the opportunity to have variables and functions with the same name, provided they are within a different scope.