Here, a global variable was defined with the value of "Hello, World!", and the function that was called had access to that variable and logged it to the console.
Global variables may be useful for smaller sites and code examples like this one, but they can cause problems in larger-scale projects and web apps.
One of the main reasons why globals can be harmful is variable naming collisions, which occur when a function creates or references a variable whose name has already been taken by a different variable that is a global.
In this example, the variable name which has a collision is
For example, Rasmus Lerdorf, the creator of the PHP programming language, worked at a company which had a very complicated bug involving globals and collisions. In order to find the bug, he printed out thousands of lines of code in paper and highlighted them until he found two globals with the same name colliding with each other, in completely unrelated places in the code. If you would like, you can hear more about this at his talk about 25 years of PHP.
IIFE's Help Fix the Globals Problem
Globals are frequently created because of code that is in the global scope, not in functions, whether those functions are explicitly defined, or used in DOM events or wrapped in a statement like
IIFEs are written by wrapping a function in parentheses, and then calling that function like normal with
Here is an example of a program without an IIFE, which pollutes the global scope:
Now, with an IIFE:
With the introduction of ES6 Arrow Functions, IIFE's can be further shortened like this:
When to Use IIFEs
In many more complex programs and web apps, it can be helpful to eliminate global variables altogether. In that case, there would be little to no global code defined — code would be defined in functions and IIFEs.
For smaller sites and scripts, I would personally simply recommend actively trying to use IIFEs whenever possible, and limiting global code. I personally do use global variables in some basic sites for brevity, but it's important to have a clear understanding of what your code's global scope looks like and what sorts of unexpected problems could occur based on that.
I hope you enjoyed this article and found IIFEs to be something you could use in future projects and scripts.
Thanks for scrolling.
— Gabriel Romualdo, February 29, 2020