I am coming from a Python background & have recently started learning Javascript. I am a bit hung up on how functions are assigned to variables & how they return data.
Please consider the following object:
const stats = {
max: 53.8,
min: 34.9,
std: 6.5
};
When I just declare a plain function & log, I get the appropriate output:
function half(stats) {
return (stats.min + stats.max) / 2.0;
};
console.log(half(stats));
However, the tutorial I am referring to uses a somewhat weird way to get the same thing done, like so:
const half = (function() {
return function half(stats) {
return (stats.min + stats.max) / 2.0;
};
})();
console.log(half(stats));
What I do not understand here is:
- The need for two nested returns (Seems fairly simple function, I don't see why we need 2 returns)
- The parenthesis that starts before the
functionkeyword & ends with the larger block - Most intriguingly, the
();at the end of the entire block, implying the function is being called as soon as it is declared?
Also, when I try to rewrite the same thing in a simpler way using my experience in Python, that seems to do the trick as well. Like so:
const half = function(stats) {
return (stats.min + stats.max) / 2.0;
};
console.log(half(stats));
Can anyone please explain to me what's happening in the code provided by the tutorial? Also, perhaps you can do so by answering the 3 questions I posed above. Thank you!