Posted in Frontend

Let’s keep the global scope clean

Have you ever seen this in a Javascript file and wondered what its for?:

(function() {

})();

This is called a IIFE function (Immediatly-Invoked Function Expression) and is used to encapsulate the scope of your code. Is is an anonymous function that is executed right after it’s created. Everything inside this function is out of reach from the outside. And if you didn´t know, everything you declare in a JS file gets assigned to the global variable “window”:

var foo = 'bar'; // This is now a global variable (window.foo)

If the code needs access to the global scope, it can be passed into the IIFE function like this:

(function(window) { // can be named anything here
    'use strict';

    function Point(x, y) {
        this.x = x;
        this.y = y;
    }

    window.Point = Point; // assigning the above constructor to global.

})(window); // Here we pass it in

Leave a Reply