DEV Community

Viraj Chavan
Viraj Chavan

Posted on • Originally published at virajc.tech

8 6

JavaScript tip: How to properly isolate your code using Anonymous Closures (IIFEs)

JavaScript code can get really messy when we keep adding random functionalities as the requirements come.

And most of the times, any new functionality you add to an app should not interfere with the existing code in your app.

You don’t want the new piece of code to override your existing variables/functions accidentally. When such code causes some unexpected behaviour, it can get really annoying to debug through multiple files.

To achieve this, our new code should run in an isolated environment. In JavaScript, closures can help us do that. Closures are the primary mechanism used to enable data privacy in JavaScript.

This is how an anonymous closures looks like:

(function () {  
    // ... all vars and functions are in this scope only.  
    // still maintains access to all global variables  
}());
Enter fullscreen mode Exit fullscreen mode

Just put your code inside of this function, and it will have its own scope while keeping the global scope pollution-free.

This is also known as a Self-Executing Anonymous Function or Immediately Invoked Function Expressions (IIFEs).

Variables declared inside the closure are not accessible outside it, but it still can access/create global variables. (The use of global variables should ideally be avoided though, they are known to be evil.)

All of the code that runs inside this function lives in a closure, which provides privacy and state throughout the lifetime of our application.

If we need to, we can expose variables/methods by returning them in the function.

var result = (function () {  
    var name = "Harry";   
    return name;   
})();

console.log(result); // "Harry"  
console.log(name); // "error, 'name' not defined"
Enter fullscreen mode Exit fullscreen mode

JavaScript Closures is the main idea behind the Module Pattern in JavaScript, you can explore the basics of module patter here:

http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html

https://dev.to/tomekbuszewski/module-pattern-in-javascript-56jm

Find me at https://virajc.tech

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay