I'm writing a introductory JavaScript tutorial series, I have a question about terminology.
When explaining the Array.prototype methods, I've given an example of some code like:
const letters = ['a', 'b', 'c'];
letters.forEach((value) => {
console.log("the value is: " + value)
});
I've said what's happening here is:
- Firstly, we're calling an object function (a function that belongs to an object, in this case the object is the
letters
array).- We pass as the first and only argument, a function:
(value) => {//...}
This is commonly known as a lambda or anonymous function.. (Unfortunately AWS Lambda functions, which is a service provided by Amazon confuses the terminology a bit 😭 )- That function has a parameter
value
, that is is going to be the current element as the we iterate over the array.- We print the value.
So the first question is, say instead my code looked like:
function printCurrentValue(value) {
console.log("the value is: " + value)
}
const letters = ['a', 'b', 'c'];
letters.forEach(printCurrentValue);
- Would we still call that an anonymous function? After all, it it is now assigned to a variable.
- Would we still call it a lambda function?
That is - intuitively I would say an anonymous function is any unnamed function, whereas I would still want to say that a named function can be used as a lambda function, as would be the case here, because lambda function, if you'll excuse my vagueness, is a 'a function that produces one value from another or something', I'm sure there's a better definition.
Elsewhere in the tutorial, I want to talk about callbacks.
For example, I might have some code like:
fetch('/user')
.then((res) => res.json())
.then((json) => console.log(json));
Where (res) => res.json()
and (json) => console.log(json)
are callbacks and they are also anonymous functions - but I'm not sure it's correct to call them lambda functions.
That is, I would define a callback as 'a function that is called else where in your application'. By that definition, the lambda functions passed into an Array.prototype method are callback functions.
Is there a tidy way to differentiate between the three terms?