DEV Community

Discussion on: Explain Closures to me like I am five

Collapse
 
lexlohr profile image
Alex Lohr

A closure is a bit like a time capsule: the things you have put into it will be the same even if outside of it things change. The interesting thing in programming is that this time capsule will create a perfect copy, so you can still use whatever you put into it elsewhere.

So let's say you have a program that will snap a picture of each passing car and writes its license plate on a blackboard to be checked against a list of stolen cars. Unfortunately, the program that does the check is a bit slow, so a lot of licenses get overwritten in the meantime. "Not on my watch!", you think and go to find a solution.

To solve the problem, you use this trusty time capsule called "closure" to make perfect copies of the blackboard every time a license is read to be checked against the list. Even though the blackboard changes a lot of times, the copy inside the capsule that gets send to the list check remains the same. Now no stolen vehicle will go unnoticed and thus you saved the day!