Once upon a time, a little code witch had her first mock technical interview. Her interviewer was super nice, but he asked her lots of questions using terms she had studied, but couldn’t quite remember or explain. She felt quite stupid and discouraged.
When her interviewer showed the code witch an actual example of said technical terms, she literally facepalmed. Now that she could see the code, the little code witch could clearly explain what was happening. The interviewer congratulated her, and she felt slightly less dense.
The code witch realized she spent so much time reading and learning a broad swath of coding concepts over the past few months, but she rarely stopped to smell the roses. She didn’t dig deep into confusing or interesting concepts because the curriculum just kept moving forward, and she couldn’t afford to lag behind.
Now that the code witch is a Flatiron School graduate, she has time to explore the intricacies and nuances of programming. With a set jaw and an eager heart, she created a list of vocabulary terms and confusing topics. Now, the code witch can explore these concepts, work them into her code, and record her findings in her spellbook… err… blog.
Here is her first entry:
Consider lexical scoping. A closure’s scope has at least three levels:
- Its own, local scope
- Its parent scope (and any grandparents)
- The global scope
Because of this, closures are useful for emulating private variables. While the closure has access to its parent’s variables, the parent can’t access the closure’s variables.
Let’s look at an example, using one of the little code witch’s favorite spells:
See? Closures aren’t that scary, though the Macbeth witches sure are. There are a couple of drawbacks to using closures in your code, however. First, closures have the potential to cause memory leaks because they can’t be garbage collected until the entire program is done using them. Closures can also lead to some unexpected results when used within loops. Luckily, MDN has a good explanation of how to avoid this in their docs.
- MDN - My husband is a technical writer, folks. Always look at the docs. Somebody worked hard to answer your questions before you even thought to ask them.