you need to understand the power of a function in js
--- to answer your question there are many benefits, just like art, it gives programmers - it gives us the flexibility to do things the way we want them to be.
---- you will get to use them soon enough as you write more code. don't worry too much for now just understand them.
functions are first-class objects which means they can be:
- stored in a variable, object, or array.
- passed as an argument to a function.
- returned from a function.
two of these happened in the above code -
it was:
- stored in a variable.
- returned from a function.
this brought us to three types/class of functions
- functions stored in variables without a name are called anonymous functions.
An anonymous function is a function without a name.
example:
let show = function () {
console.log('Anonymous function');
};
show();
or the no-name enclosed function inside half variable in your code above
- another part is half variable being an Immediately-invoked Function Expression or self-invoking expression
A self-invoking expression is invoked (started) automatically, without being called.
Function expressions will execute automatically if the expression is followed by ().
e.g
(function () {
var x = "Hello!!"; // I will invoke myself
})();
or the no-name enclosed function inside half variable in your code above is a self-invoking function.
putting the two together --- half variable above is an anonymous self-invoking expression that means it contains an anonymous self-invoking function
- one last thing --- closure and higher-order function.
A closure is a function having access to the parent scope, even after the parent function has closed/called.
that function half can be deemed as a closure. in case there is a variable inside the anonymous self-invoking function pitted to half variable, it will have access to the variable even after half expression has been called.
A higher-order function is a function that takes another function as an input, or returns a function, or does both.
the anonymous self-invoking function can be called an anonymous higher-order function because it return another function.
read more here
https://www.freecodecamp.org/news/discover-the-power-of-first-class-functions-fd0d7b599b69/
https://www.w3schools.com/js/js_function_closures.asp
https://www.freecodecamp.org/news/a-quick-intro-to-higher-order-functions-in-javascript-1a014f89c6b/