In your programming interview, you may be given an example like this:
JavaScript
var addFive = createBase(5)
addFive(8) // returns 13
addFive(16) // returns 21
And asked to solve it or make sense of it.
The question is how can we access the base value of 5 in the subsequent (and future) addFive() function calls?
Hey, Tyler here. I’m building Formyra, an AI-powered smart forms platform that helps businesses automate workflows, cut busywork, and turn form submissions into real growth.
If that sounds interesting, I’d love for you to check it out!
The answer is closures.
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
Below I'll show you how you can create closures both in JavaScript and PHP to answer the interview question above.
If you'd rather see this post in video format, watch the video below and be sure to subscribe to my YouTube playlist Tyler Answers Interview Questions.
In JavaScript, a closure is just a function that returns a function. Here's how we can make the interview question work:
JavaScript
const createBase = base => {
return (n) => {
return n + base
}
}
const addFive = createBase(5)
addFive(8) // returns 13
addFive(16) // returns 21
Because of the closure, we are able to access the base parameter inside of the returned function after the fact.
Our PHP solution is nearly identical adding only one necessary keyword: use. Use lets us pass parameters to use in closures.
PHP
function createBase($base) {
return function($n) use ($base) {
return $n + $base;
};
};
$addFive = createBase(5);
$addFive(8) // returns 13
$addFive(16) // returns 21
By passing the $base parameter via use we can add it to $n and return the sum.
Tweet me @tylerewillis