codelikeapoem-scoping-issues

The Bad and The Worse – JavaScript Scoping Issues

Hope you all gone through how amazing JavaScript worker is. Today, we learn something core to JavaScript. Every language has its bad sides or “How not to use/write code” like that. Lately, I wrote JavaScript more than 3 years now and felt I using it well. But, every time looks back and read see my code a couple of months back, it looked awful. Over the times, I kept on learning and improving thanks to my mentor and colleagues. I started using Linters and learned what are the ways to write and ways not. So this about the bad side of JavaScript and especially Javascript scoping issues, which is the pillar in understanding this language for proper use.

JavaScript Scoping Issues

To know the JavaScript scope issues, first, we have to understand about global variables how it works and what is the scope.

Understanding Global Variables

Global variables or variables belonging to window are the great aid to newbies, Just assign a value in a global it can be used anywhere. Its pretty helpful, but, you don’t how bad it is until you are code starts getting bigger and bigger till you end up not knowing where the variables it declared.

Take this simple code,

As you can see thisIsGlobal is declared outside the function which automatically becomes a global level variable, it can be used anywhere. Can anyone see the problem here?

In the function foo I’m just directly using a thisIsGlobal. If the function foo becomes big, you will have no idea where this variable come from.

 

This example shows the badest way to use a variable. The variable ‘poem’ becomes global, function getPoem becomes global. Based on the order of usage in index.html, they are overwritten.

Solving This:
Never use a variable outside the function or put a function directly in a file. Better way to do this wrapping it like this,

The Scope & JavaScript Scoping Issues

What is scope? It is nothing but,

A block of statements wrapped in a curly braces. The one we seen previously is called ‘Global Scope’. And there is, Local/Functional Scope and Block scope (Recent JavaScript version)

Okay, the bad stuff here, when compared to other languages like PHP, is, if you forgot to var inside the function getPoem, it will automatically become a global variable.

Solving This

Always use var keyword inside a function in the very first line it starts.
Avoid global usage even intentionally

And Block Scope
The let is something new, its only supported in few browsers which support block level scope

Hope it makes it clearer about how scoping works in JavaScript and how it won’t show any errors or warning. Understanding how scope works and its usage and flaws are must for any developers.