Exploring JavaScript Functions: Types, Differences, and Best Practices

Introduction

JavaScript has many fundamentals but not all of them can be considered the backbone that allows your code to function. Puns aside, a good written function will allow you to empower your web application and cultivate your target audience with convenience. Nevertheless, we’ll have to dive into the various function types to ultimately decide which type of function is best for what we are attempting to achieve and what exactly makes that function the ideal choice given that goal.

Main Focus

As previously mentioned, we will need to go over what exactly makes each function type unique and begin finding ways to utilize those traits. As there are many to choose from, we will limit this down to going over the syntax and use of the following function types:

  • Function Declarations

  • Arrow Functions

  • Anonymous Functions

  • IIFE (Immediately Invoked Function Expression)

Additionally, we will briefly discuss the best practices for each function type and naming conventions that will allow your code to be readable and concise.

Code Examples including best practices and use cases

  • Function Declarations are a function that have a specified name and are declared with the function keyword. These can typically be called later in the code you create. These functions will also be hoisted, meaning they can be invoked before the literal line they are written on.

    • Code Example:

        // The below line declares a function with the parameter that is
        // named parameter. It will execute on what is within the {} - 
        // also known as curly brackets.
        function exclamation(parameter) {
      
        // The below line will output the results of the concatenation 
        // of the text 'Hello, World' and the value of the parameter named
        // parameter. The naming convention of the parameter can typically be
        // more accurate in terms of what it is calling for. 
          console.log('Hello,  World' + 'parameter');
        }
      
        // The below line is calling the exclamation function declaration and 
        // the inputted '!' is passed as an argument.
      
        exclamation('!');
      
  • Arrow Functions are functions that are the more concise way of writing a function in comparison to a function declaration. Arrow functions also have the ability to utilize lexical scoping (closures), and the ability to inherit the this value from the enclosing scope when they are established. A special note about arrow functions - they do not need a return if everything is on one line! (see Anonymous Functions code example)

    • Code Example:

        const functionsObject = {  // Creating a object that includes both 
            // a declaration function and an arrow function 
      
            functionDeclaration: function() {
                this.value = 1;
                // Regular function with its own 'this' context
                setTimeout(function() {
                    this.value++; // ++ is adding 1 to the existing value
                    console.log(this.value); 
                }, 1000); // this.value results in NaN (loses context)
            }, //! console.log(this) will log the function object (loses context)
            },
      
            arrowFunction: function() {
                this.value = 1;
                // Arrow function inherits 'this' from the enclosing scope
                setTimeout(() => {
                    this.value++; // ++ is adding 1 to the existing value
                    console.log(this.value); // Results in 2 (preserves context)
                }, 1000);   //! console.log(this) will log the enclosing context 
            },
            }
      
            functionsObject.functionDeclaration() 
            functionsObject.arrowFunction()
            //calling each function through their key using dot notation
      
  • Anonymous Functions are not bound to a specific identifier and can be passed as an argument within other functions, typically higher order functions, which accept other functions as an argument or could return a function. Various built-in functions operate in this way.

    • Code Example:

      
        myArry = ['this', 'iS', 'WHAT', 'I', 'waNT', 'To', 'trY']
        // This function includes an anonymous function. 
        // Do not misunderstand, the first arrow function is assigned to
        // a variable (titleCased) and it can be called by this assigned name.
        // But, there is a second arrow function and it is annonymous.
        //! Note, everything is on one line so there is no need for a return
      
        const titleCased = (inputArray) => inputArray.map(newTutorials => 
        newTutorials.charAt(0).toUpperCase() + newTutorials.substring(1));
      
        // Takes an Array and capitalizes the first letter of each word. 
        const tutorialsCased = titleCased(myArry);
      
  • IIFE (Immediately Invoked Function Expression) is a function that is accurately described by its name – it is immediately invoked as it is defined. These were heavily utilized pre-ES6 as prior to having const and let available (block scope) as they were often used to contain the declared variables and prevent them from being available in the global scope.

    • Code Example:

        //The function is surrounded in parentheses so I can be invoked later
        const iffyFunction = (function() { 
              console.log("This is an IIFE!"); 
        })(); // This is what makes an IIFE - the function is being immediately 
        // invoked by the empty parentheses, following the closing ")"         
        // parentheses that is opened at the function declaration
      

Conclusion

Without a doubt functions are not only required for a modern day program but also have specific uses that allow JavaScript programmers to create intricate code that leverages both readability and efficiency. Keep in mind we only touched on a portion of the available function types and some additional function types can be further researched:

  • Function Expressions

  • Generator Functions

  • Callback Functions

  • Recursive Functions

  • Constructor Functions

  • Built-in Functions (commonly referred to as methods)

  • Closures

Additionally, we briefly discussed some JavaScript terminology but these concepts can also be greatly expanded on:

  • Hoisted function

  • Lexical scoping

  • Higher order functions

  • Block scope

  • Pre-ES6

References

Functions MDN

Closures MDN

Arrow Functions MDN

IIFE MDN

"this." Operator MDN