DEV Community

Roger Campbell II
Roger Campbell II

Posted on • Edited on

Understanding Scope in JavaScript

Quick Summary

Global, Local what do they mean. In this blog post I will help explain how scope works and how to better implement it into your code.

Requirements:

  • A basic understanding of JavaScript.
  • Text editor of your choice.
  • A willingness to learn.

Introduction

Scope is a feature within JavaScript which allows you to dictate the lifespan, access, and visibility of variables, functions, and objects in your code.

In order to understand how scope works within a JavaScript document I believe one should first understand some of the key benefits of scope.

  • Security- Scope allows you to limit access to variables and functions so that they can be called only at times when they are needed.
  • Reduces Namespace Collision- Can occur when two or more variables share the same or similar names. When you properly utilize scope, you reduce your risk of N.S.C.
  • Code Reusability – When you properly use local scope your code becomes more dynamic and reusable with less chances of possible side effects.

Types of Scope:

  • Global
  • Local

Global Scope:

The moment you begin to write code in a JavaScript document, you are in the global scope. You are able to access any global variable functions, objects, etc. from the inception of your application until it. Any variables, functions, objects, etc. you define in the global scope is available.

Below I have defined a variable called ‘glabalRabbit’ in the global scope.

Now that we have defined ‘globalRabbit’ let’s console.log it to return its defined value.

Local Scope:

Anytime you create a function and define a variable within it, you are creating local scope. This means that if you were to use the same variable name in two separate functions, they would not cause a namespace collision. Although using the same variable name anytime in your code is not considered best practice.

In the example below, I have created a function named localScope and defined a variable called localRabbit.

Now let’s test our global scope variable.

Below we can see that when we console.log(globalRabbit) above, below, and inside of our newly created function we are able to return its value.

Next let’s test out our local scope variable.

As you can see when we attempt to console.log(localRabbit) we are only able to return its value inside of the function in which it is defined.

Pro Tips

  • Global scope begins the second you begin to type in the JavaScript document.
  • Local scope is defined when you create a function.
  • Stir clear of using the same name variable name for different instances.

Top comments (0)