Understanding scope is crucial to writing successful code, and can help you avoid introducing bugs that are hard to trace. I made the MONUMENTAL mistake of using a bunch of global variables in my first project at Flatiron School, which made it very difficult to trace where the issues in my code were coming from. It is safe to say that making mistakes and failing at something is a powerful teacher. I will certainly never forget that lesson. Anyways, here I will introduce the concept of variable scope in JavaScript.

Global Scope

Globally scoped variables are declared outside of functions or blocks and are available anywhere on the window object. They can be defined using the varlet, or _const _variable declarations.

Image for post

It is best to avoid global variables, keep code modularized, and keep functions and files specific to a certain purpose. Like keeping an organized closet where you know that your shoes, pants, shirts, jewelry, etc are all in a specific area where it is easy to find where something is located, rather than throwing all of your items in a pile on the floor. Any time you go looking to find where a certain item is located, it will take you a long amount of time just to sort through it. If you keep variables local to a specific function with a specific purpose, you will have a much easier time keeping that file organized. If you need to go back and debug something, you know that the issue is local to the function.

#javascript #variables #coding #flatiron-school #function #programming

Introduction to Scope in JavaScript
1.10 GEEK