Function Parameters and Arguments
Quick recap on simple functions
Previously in Part 1 of An introduction to functions in Javascript, we looked at the basics of declaring functions as well as calling or invoking them. We also touched on passing arguments as values to a function when invoking it.
The important thing to remember is what we’re doing. Two very simple things actually. We are DEFINING a function. The second thing we are doing is INVOKING (calling) our function.
When we define our function we may also define it in such a way that we are expecting some values to arrive which we need in order for the function to then work with and continue its job. What the function does with these values is defined by the programmer. The function definition is just that. It defines or intimately tells anybody who looks at it, precisely what its purpose is and what it does. You know this because you give it a meaningful name when preceding it with the keyword ‘function’.
Before we go any further, just a reminder that not all functions expect incoming values to arrive which they then go ahead and work with. A function can simply be something that outputs a message when invoked as shown in the next example below. Notice its a function definition for a function which does not expect any incoming values to work with. Its job is to simply output a message onto the screen.
The above should be pretty clear to you. When the above function is executed, the line “Apple, Orange, Pear, Banana” is outputted into the console. That is all that happens here.
Sending array objects as arguments
In the example below, a function named ‘displayFruits’ is defined and has a parameter named ‘fruitsList’. The name of the parameter along with the name of the function ought to reveal to an extent, what it does and what its purpose is. The parameter here is named ‘fruitsList’ and it behaves as a ‘placeholder’ for an incoming argument value.
This argument value is actually an array object which we define outside of the definition but before we invoke the function. When we invoke the function we pass the array object as an argument to the ‘displayFruits’ function call. The entire array therefore is passed when we invoke the function.
Finally in the function definition, a for loop iterates through all the values of the array and outputs a message for each fruit using the builtin alert function in javascript.
What are anonymous functions?
In JavaScript, you can also declare what are called anonymous functions. Anonymous functions are functions that do not have a name. Instead, they are created on the fly and typically used as a value for a variable or passed as an argument to another function.
Here’s an example of an anonymous function:
In this example, the ‘myFunction’ variable is assigned an anonymous function that logs “Hello, world!” to the console when called. Notice that this function does not have a name, but can be called using the ‘myFunction()’ syntax.
You will most likely see anonymous functions being used in JavaScript whenever we need to create closures, as well as to pass functions as arguments to other functions. They can be particularly useful for creating small, reusable functions that don’t need to be named or referenced in multiple places in your code. Another commonly used term for anonymous functions is ‘function expressions’ since they can be assigned to variables as shown in the above example. They can also be passed as an argument to other functions and do not need to be declared using the ‘function’ keyword.
Anonymous functions are commonly used in JavaScript for callbacks, which are functions passed as arguments to other functions to be executed at a later time. Here’s an example of using an anonymous function as a callback:
The setTimeout function takes as its argument a nameless function which is our anonymous function. After 1 second, a message is outputted onto our console ‘Timeout complete!’.
Anonymous Functions as IFFEs (Immediately Invoked Function Expressions)
When an anonymous function is not being used to create a closure or being passed to another function as an argument to be called at a later time (callback functions) then they’ll be simply used by themselves in the form of IFFEs.
It is worth noting, that anonymous functions are essentially nameless function expressions, that is, they are anonymous and are not called by name. When they are invoked or ‘called’ immediately, that is when we refer to them as IFFEs.
What are IFFE Functions?
IIFE, or Immediately Invoked Function Expression, is a JavaScript design pattern that involves creating and executing a function immediately after its definition. This pattern is particularly useful in certain situations to create a private scope for variables, manage function execution order, and avoid polluting the global namespace.
Here’s a breakdown of the key components and the reasons for using IIFE in JavaScript:
1. Definition:
An IIFE is created by wrapping a function expression within parentheses and immediately invoking it. The basic syntax looks like this:
The anonymous function is enclosed in parentheses, and the final pair of parentheses at the end execute the function immediately.
2. Private Scope:
One of the primary reasons for using IIFE is to encapsulate variables within a private scope, meaning they they can only be used inside their existing functions. Variables declared inside the IIFE are NOT accessible from the outside, preventing potential conflicts with other scripts or libraries. This helps avoid unintended variable overwrites and promotes cleaner code.
To further help you understand private scope and variable encapsulation, in the example code snippet below two variables are declared with the same name: One variable is declared with global scope while the other, with private scope. The variable that is declared with global scope has a different value compared to the variable declared inside the IIFE which has a private scope.
3. Preventing Global Pollution:
JavaScript’s global namespace is shared across scripts and libraries. IIFE helps prevent global pollution by keeping variables and functions local to the IIFE, reducing the risk of naming collisions as was demonstrated in the above code.
4. Function Execution Order:
One of the great things about using IIFEs is that they allow you to control the order of function execution. This can be particularly useful in scenarios where you need to ensure that certain code runs before the rest of the script.
If you want the IIFE to return a value or make something accessible to the outside code, you can modify it to return a value or assign properties to a global object. Here’s an example:
In this example, the result
variable is declared in the global scope before the IIFE. Inside the IIFE, the result
variable is assigned the value of 2 * secretNumber
. As a result, you can access the result
variable outside the IIFE, and it will contain the calculated value. Keep in mind that using global variables should be done judiciously to avoid unintended side effects and potential naming conflicts. If you want to encapsulate the result, you might consider returning an object or using a module pattern.
5. Module Pattern:
IIFE is often used in conjunction with the module pattern to create modular and maintainable code. By returning an object or function from the IIFE, you can expose only the necessary parts of your code while keeping the rest private. This is demonstrated in the example below:
In summary, IIFE in JavaScript is a powerful tool for creating private scopes, managing variable visibility, and controlling function execution order. It is commonly employed in scenarios where encapsulation, avoiding global namespace pollution, and modularization are important aspects of the codebase.
Sarah Gunn says
Great article, say I last viewed your blog almost a year ago. Any plans to add new content Manoj? Please do as I find your explanations and tutorials very easy to understand and follow. I look forward to seeing more of them!
Manoj Kumar says
Cheers Sarah!
Though I’ve been inactive for a while, I’ll defo be putting out some new articles in 2024 so do keep a lookout for that. In the meantime, Thank you for your kind words.
Saima Haider says
Great article and well explained.
Manoj Kumar says
Thank you Saima for your kind words, I’ll be putting out some new content on my blog so keep your eyes peeled for that in 2024.