This page looks best with JavaScript enabled

Avoid Scope Pollution in Javascript

 ·   ·  ☕ 1 min read

It is quite easy to pollute global scope by defining variables or functions that impact core functions.

1
2
3
4
const parseInt = val => console.log("int parsed: ", val);

parseInt(1);
// int parsed: 1

parseInt has transformed into a printer, thanks to the above code.

The practice of “overriding” global scope is not useful and should be avoided like the plague (If you are born in the wrong century - “plague is to be avoided at all costs”). Using such declarations -

  • cause confusion
  • introduce inconsistencies
  • cause confusion

Yes, “cause confusion” is repeated for clarity.

The next time you see a function behaving badly, check for such declarations first. For some reason, some developers end up thinking that it is a good idea to tackle the psychopath of a maintenance engineer.

But, if you inherit such a function and cannot quite change it at this time - you may want to “pass” the global reference to such functions/modules/classes. Refer to those global scopes all the time for any future changes.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things