I recently interviewed a candidate for an entry level web developer position and asked this question: What might you call the following line of code in Javascript:
let foo = function() {}
The question was purposefully vague because the resume was weak and I wanted to get a sense of how the candidate worked through all of the possible answers to the question. After a few moments the response was essentially "I don't know, what's the right answer?"
I explained that there are a few answers: Variable declaration, function assignment, hoisting mitigation, ES6, etc. Then I said it could also be considered a closure. To that, the candidate responded, "I don't think that's a closure. A closure is a function inside of function."
It's the first time I've ever had a candidate challenge my response to a question to which they didn't know the answer and it made me wonder if a closure could be boiled down to a simple one liner. Am I wrong about that?
Edit: This is only for my own learning and has nothing to do with the candidate. In fact, we extended an offer and they accepted. They start next week :)
I think we can agree that a function doesn't have to be defines inside another function to be a closure. I'd probably have followed up and asked why they think that that's a requirement for being a closure and then direct the conversation towards scope in general.
People may have different opinions about what really constitutes a closure, but I like the description from Wikipedia (which used to be a bit more extensive) which I have been using whenever I teach JavaScript:
Operationally, a closure is a record storing a function together with an environment.
I like it because it is a very easy to understand description, and it applies easily to JavaScript functions, because that's exactly how it works as described in the spec. The spec even uses the term closure to refer to a created function, irrespectively of the actual content of the function.
And following that thought, every function in JavaScript is a closure, so you are right.
Having said that, I could see someone making the argument that this function is not used as a closure, since it doesn't access any free variables.
I also have to add that "closure" wouldn't be the first thing that comes to my mind when looking at this code. It's easier to name the things that are there vs that are not there (referring to the function not be used as a closure).
The first thing that would come to my mind is function expression.