Image composed by Aphinya Dechalert. Unlocking the secrets to closures.

Understanding Closures in JavaScript

It’s actually a lot simpler than what other tutorials are trying to tell you

Aphinya Dechalert
Published in
4 min readFeb 27, 2019

--

JavaScript closure is one of those topics that can be hard to wrap your head around, simply because of how it’s often explained. Most tutorials just tell you that it’s a function within a function — but in reality, there is deeper meaning behind it all.

“Writing in ECMAScript language without understanding closure is like writing Java without understanding classes” — Douglas Crockford, father of JSON

Lets look at the code below:

a simple little piece of code

However, the above code is not very efficient. It uses a global scope and there is nothing to protect it against change.

A lot of people often forget that JavaScript is a lexical scoping language. This means, inheritance flows inwards. A variable outside a function is available for usage within a function but not the other way around.

You can’t use a value that’s been declared inside a function outside it.

--

--

Aphinya Dechalert
Modules&Methods

Where Development Meets Storytelling: Tech Writer, Editor & Dev Advocate. Translating Complexity into Clarity. DM me. linkedin.com/in/dechalert