It took me a while to understand the concept of closure in JavaScript, but it can be easily visualized with a familiar analogy.

In police procedurals, suspects are sometimes brought into an interrogation room that contains a one-way mirror. The police officers outside the room can observe the interrogation that is happening inside the room through the glass panel, but the suspect and the interrogator inside the room can’t see outside through the same panel.

In JavaScript, it’s the other way round. Someone inside the room can see what’s outside, but someone outside can’t see inside. The objects inside the child scope (inside) have access to variables in the parent scope (outside), but objects in the parent scope have no access to variables in the child scope.

To illustrate this, let’s use The Silence of the Lambs, one of the best thriller films ever made.  In this scene,  FBI trainee Clarice Starling meets the incarcerated cannibalistic serial killer, Dr. Hannibal Lecter, for the first time.

In our absurd remake of the scene, Dr. Lecter’s cell has a one-way mirror where he can see the outside, and those outside can’t see him. Clarice slowly walks down the hallway of the prison. She has seen Dr. Lecter’s files, but she has no idea what he sounds like, and she doesn’t know which cell he is in. As she walks by Dr. Lecter’s cell, he sees her, and says something to her.

The computer says inmate is not defined because Clarice, who is outside the cell (in the parent scope), cannot see the inmate who is inside the cell (in the child scope). On the other hand, Dr. Lecter, who is inside the cell (in the child scope), can see the agent who is outside the cell (in the parent scope).

Since Clarice can’t see who’s inside, she is not able to respond with a greeting. She must enter the cell to see who she is talking to.

Now they’re talking. Clarice is terrified by the presence of Dr. Lecter, so she turns around and walks out, and Dr. Lecter follows suit.

We don’t know what happened to Clarice afterwards, but now we know a little bit about JavaScript closure.