Function Declaration vs Function Expression vs IIFE
Type of functions in JavaScript and when to use them.
Overview
Good day everyone!
Today I'll be reviewing the different methods of creating functions in JavaScript. As you go through the basics of the language, it may be a little difficult to grasp the importance of one function over the other, but different coding scenarios may call for different approaches. Throughout this post, I will explain how each function is declared and some important differences to note from each function type.
What is a Function?
First, let us clarify what a function in JavaScript is. When writing a script, you will most likely come across repetitive instructions for whatever task you set out to execute. Constantly rewriting instructions can become tedious and could lead to messy code files, which we all know is bad for our future self when we want to refactor our code.
In programming, one tool we can use for repetitive code is functions. With functions, we can give a name to a group of instructions (or 'block of code') and call on this group whenever we need a specific action to be executed. In JavaScript, we can use the function
keyword to declare a function. Any code that is placed within the curly braces is code that will be executed when we "call" on the function.
Here is an example to clarify:
// Instructions for our Robot
/*
console.log("move right");
console.log("move right");
console.log("move forward");
console.log("move forward");
console.log("move forward");
console.log("move left");
*/
// Hoisting function using its identifier
moveToCheckpoint(); // will still execute
// function to instruct our robot
function moveToCheckpoint() {
console.log("move right");
console.log("move right");
console.log("move forward");
console.log("move forward");
console.log("move forward");
console.log("move left");
}
// call function to instruct robot
moveToCheckpoint();
In this example, we used the "standard" way of creating a function. This method is known as Function Declaration. With this approach, we can call the function before its declaration. This is known as "hoisting" the function. The block of code will still execute as intended even if we call it before its declared. This is useful when we want to call a function at any point in a script.
Function Expression:
As opposed to function declaration, Function Expressions are functions that are assigned to a variable. Let us take a look at the following example:
// assigning our function to a variable
const robotInstruction = function moveToCheckpoint() {
console.log("move right");
console.log("move right");
console.log("move forward");
console.log("move forward");
console.log("move forward");
console.log("move left");
}
// creating our function expression anonymously (no identifier)
const robotInstruction2 = function () {
// sample code here
}
// creating our function expression using arrow functions
const robotInstruction3 = () => {
// sample code here
}
// call function expression using variable
robotInstruction();
// calling function directly
moveToCheckpoint(); // This works as well
Here, you can see our created function used as an expression that is assigned to a variable name. The important thing to note here is function expressions are not hoisted. This means you cannot call the function before creating it.
This method of creating functions can be useful when you want a function to only be created at a certain point in a script. Also, you may want to limit a developer's ability to call the function. Finally, if you wish to keep a function anonymous (no identifier), you can use function expressions just for that!
Immediately Invoked Function Expressions (IIFEs):
As the name implies, Immediately Invoked Function Expressions (IIFE) are functions that are invoked (executed) immediately. So as soon as you compile and run your script, these functions are executed and the code inside them is executed as well.
// creating IIFE
(function () {
console.log("move right");
console.log("move right");
console.log("move forward");
console.log("move forward");
console.log("move forward");
console.log("move left");
})()
// This will run as soon as we run our script file
// creating IIFE using arrow function
(() => {
// sample code here
})()
// putting the final parenthesis inside the grouping operator
(() => {
// sample code here
}())
// this will work as well
Notice that our function is encased in parentheses before the function
keyword and after the closing curly brace. These parentheses are known as the grouping operators. This lets the JavaScript interpreter know that this function is an expression and should be treated as such.
The empty parentheses that follow the grouping operators are known as the final parentheses. This lets the JavaScript interpreter know to execute this function expression immediately. It does not matter if you put the final parentheses within the grouping operator or right after it, it will still act as an IIFE (just make sure you include both!).
You might wonder when it would make sense to use an IIFE. It is useful when you want to protect the variables used within the function. Say you have variables with the same name used in other scripts. Since the function expression is executed right away, this prevents any global variable conflicts from occurring. IIFEs are also great for when you want a specific task to occur once when a script is loaded. This can help with performance in your application and prevent certain functions from repeating.
Final Thoughts
Although I have not found a use case yet for IIFEs, I hope to know when to use them if I come across a possible scenario in the future. I hope this article helped with your understanding of JavaScript Functions and feel free to reach out if you have any additional questions or comments!
Thank you for reading and happy coding! ๐จ๐พโ๐ป