ost developers today, know about closures in Javascript. Don’t be sad if you don’t, it’s not something you generally use on your every-day work (well, you may, but it’s not so common).
losures are something that many companies would like you to know before working for them, therefore, chances are they’ll ask you something related with this topic, or even more, they could make you write a practical example of it.
On this story, I’m gonna tell you about a small function I was asked to develop on an interview a while ago, that involved the use of closures for its solution.
Let’s start with the premise:
Can you write a function that will solve the following test case?
let result = sum(1)(2)(3)();
console.log(result === 6 ? 'SUCCESS' : 'ERROR');
The function we need to create will sum the values sent as a parameter and will accumulate them. Also, it will return another function for the next value to be passed on. If we don’t send any value to it, it will return the accumulated value.
It looks fairly simple at first, but let’s take a look into it:
const sum = (value) => {
let accum = 0;
if (value) {
accum += value;
const innerSum = (value) => { /*TODO*/ };
} else {
return accum;
}
};
console.log(sum());
0
That’s a good start. First, we create the function called sum
that will take a value
as a parameter. If that value exists, we will sum the value to the accum
and return a function to keep adding values (TODO).
#currying #javascript-interview #javascript #closures-functions #closure