A photograph of the author, Alex Kharouk

Alex Kharouk

Book Club Snack: Closures, the Call Stack, and Recursion

## Quick Bites

In my last post, I mentioned that topics like closures, the call stack, and recursion deserved to be in a separate post. I'm taking it a step further, and snackifying it. Please understand though, these topics deserve much more of your time if you do decide to learn them. Also, I'll be describing them with the same perspective as described in Eloquent JavaScript.

### Closures

When we execute a function, the scope of the function and all the variables are created (and re-created every time its executed). This is great because we can comfortably know that whatever happens inside the function, stays inside the function. It's like a getaway to Las Vegas! With this knowledge, we can utilise the concept of closures. The name is properly assigned to the concept. We are closing in the scope of the function. Whenever a function references other variables outside its scope, that is a closure. This allows us to do fancy things like create functions that return functions that rely on its local state.

function signature(name) {
return (statement) => `${statement}, ${name}`
}
const mySignedSignature = signature('Alex')
console.log(mySignedSignature('Eternally yours'))
// "Eternally yours, Alex"

In this case, the argument name is a local variable that we pass to the enclosed statement function. After the signature function has finished executing, the scope has closed, and we continue onwards.

Does this mean we can have infinite closures? Yes, but most likely we never want to get close to that depth. Closures are everywhere, and most likely you've used them. A well known closure you've most likely used is within an array method like .filter().

const blogPosts = [
'Just Graduated a Boot Camp!',
'What is a Stack?',
'Growth Mindsets: A Fever Dream?',
'Working at FAANG! An Ex-FAANG Tale',
'Working at a Startup! An Ex-CEO Tale',
]
const searchQuery = 'Stack'
blogPosts.filter((post) => post.includes(searchQuery))
// ["What is a Stack?"]

Here we can see clearly how the filter method takes in another function, which accesses the searchQuery variable, outside the scope of the filter method. To really emphasise the point, we can extract the function and pass in the variable it's binded to:

const searchQuery = 'Ex'
function findPostByQuery(post) {
return post.includes(searchQuery)
}
blogPosts.filter((post) => findPostByQuery(post))
/* ["Working at FAANG! An Ex-FAANG Tale",
"Working at a Startup! An Ex-CEO Tale"];
*/

Here's a quick test for you:

What is a closure?

Incorrect!

### Recursion