First of all, in JavaScript functions
are Object
s that implement the [[runnable]]
interface. As with any other object, this can be assigned to a variable, passed around as an argument to other functions etc. The latter is commonly referred to as JavaScript function
s being first-class citizens:
In programming language design, a first-class citizen [...] in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include being passed as an argument, returned from a function, and assigned to a variable.
JavaScript has the concept of named functions, but this feature is not available for ES6 "arrow" functions (as the one you're showing).
Hence the only way to give such an anonymous arrow function a name (and thus, make it available for calling later) is to assign (always) anonymous arrow functions to a variable, which then acts as a pointer to that anonymous function.
That is exactly what is happening in your line
const half = ({max,min}) => (max+min)/2.0;
// ^^^ variable ^^^ anonymous arrow function
Also note that only arrow functions allow to omit the return
keyword and the {}
block markers around it, if all that follows is a single expression.
With "old" ES5 functions, you could outright declare a named function:
const stats = {
max: 56.78,
min: -0.75
};
console.log(half(stats));
// ES 5 function declarations are "hoisted"
// meaning you can call them in your code before
// declaring the function
function half({max,min}) {
return (max+min)/2;
}
Please also note that compared to your code, there are minor additional technical differences. Named ES5 function declarations are hoisted, which means the JS interpreter pulls them right to the top of your code, making the function available for calling even before declaring it.