Hello, I’m currently learning about function types from a JavaScript book. I would like some clarification please.
A function declaration is a function you can call later. They are named functions.
A function expression is where you put a function into a variable as an expression. Example:
var area = function(width, height){
return width * height;
}
A function without a name is called an anonymous function. The previous example is an anonymous function.
In a function declaration, you can call the function before or after.
In a function expression, you can’t call the function before it shows up in the code.
This decides which one to use.
Immediately invoked functions (IIFE) are anonymous functions because they have no name. They are executed as soon as it appears in the code.
The point of IIFEs is to prevent scoping problems.
There is usually though little benefit to using anonymous functions. They make the code harder to understand, and debugging through lots of anonymous stack traces becomes maddening.
Immediately Invoked Function Expressions
These, as the name says, invoke immediately because you place the invoking parenthesis at the end of the function.
IIFE’s don’t have to be anonymous functions. It can be beneficial to name them iife to help remove confusion about them.
var shape = (function iife() {
}());
It’s a choice of style as to whether you use }()); or })(); at the end.
I prefer to invoke the function itself as that’s more consistent with how we normally use functions.
The enclosing parenthesis around the whole function serve a couple of different purposes. It helps to inform people reading the code that something strange is happening to the function, and allows the iife to be executed when it’s not assigned to a variable.
Arrow functions
Arrow functions remove most of the syntax from defining a function.
var area = shape => shape.width * shape.height;
Multiple function arguments use parenthesis instead, and multiple statements can be enclosed within curly braces.
Arrow functions tend to result in a very functional style of coding, where data is processed by series of pipelines.
Thanks! Some of these types are new to me, as they haven’t been listed in the book as of yet. “Functions as arguments” and “Arrow functions” to be specific.
I see IIFEs are not always anonymous, but they can be.