Closures vs Global Variables…how are they different?

Dolly Desir
2 min readApr 5, 2021

--

Hello again ! I’ve been doing algo for the last month and I’m actually getting better finally but as I get into more difficult I realized I needed to really brush up on my fundamentals of JS. Closures is one of those fundamentals but when I looked into, I didn’t see how it was different than declaring a global variable. When using global variables you are able to access that variable anywhere.

In my short time of programming, I’ve only ever used global variables because that’s what I was taught. For my small applications and code challenges, using global variables are great but I can see in a real world application that has hundreds and thousands of lines of code, global variables really aren’t that efficient. Using a global for something that you’ll need through your application makes sense, for instance maybe a url but depending on how complex an application is, I could also see that not being efficient.

Closures:

A mechanism in JavaScript for handling variable scope and often used when bundling functions together. Closures are created every time a function is created.

Lexical scope

A word often used when describing closure is lexical scope. The word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope. So in the code above, displayMessage has access to the variable message even though it is outside of it own function. The message variable will never accessed anywhere else. Also displayMessage has to be invoked within its parent function not outside of it.

displayMessage() moved outside of function

As I understand it, they’re differences are in the use cases. Because I haven’t had a super complex application just yet to fully see closures in action, I can see why using closures is best practice when you have an application with a lot of moving parts. Hope this was helpful! Happy coding !

--

--

Dolly Desir
Dolly Desir

No responses yet