Different ways of writing functions in JavaScript

Js Basics

In contrast to other programming languages, JavaScript allows us to implement functions in various ways. In this article, we'll explore some of the most common approaches to writing functions in JavaScript.
PS: In the upcoming articles, we'll delve into the importance and relevance of each type of implementation.

  1. Named Function

     function add(a, b) {
       return a + b;
     }
    
  2. Arrow Functions (ES6)

     const add = (a, b) => {
       return a + b;
     };
    
  3. Function Expressions

     const add = function(a, b) {
       return a + b;
     };
    
  4. Function Expressions (IIFE)

     (function() {
       const message = "Hello World!";
       console.log(message);
     })();
    
  5. Higher-Order Functions (it takes other functions as arguments or return functions)

     function calculate(a, b, add) {
       return add(a, b);
     }
    
     const result = calculate(5, 3, (x, y) => x + y);
    
  6. Generator Functions (ES6)

     function* generateNumbers() {
       yield 1;
       yield 2;
       yield 3;
     }
    
     const numberGenerator = generateNumbers();
    
     console.log(numberGenerator.next()); // { value: 1, done: false }
     console.log(numberGenerator.next()); // { value: 2, done: false }
     console.log(numberGenerator.next()); // { value: 3, done: false }
     console.log(numberGenerator.next()); // { value: undefined, done: true }
    

    Note: Generator functions are different from regular functions in that they can pause and resume their execution, enabling you to generate a sequence of values gradually. When a generator yields a value using the yield keyword, it stops its execution temporarily and saves its current state. The next time you call the generator next() method, it continues where it left off, utilizing its saved state to resume execution until it reaches the next statement or the end of the function.

  7. Anonymous Functions

     setTimeout(function() {
       console.log("This is an anonymous function used as a callback.");
     }, 1000);
    
  8. Recursive Functions

     function factorial(n) {
       if (n === 0) return 1;
       return n * factorial(n - 1);
     }
    

In conclusion, JavaScript offers a versatile set of function types that empower developers to build dynamic and efficient applications. From the simplicity of named functions to the conciseness of arrow functions, each type serves a unique purpose and contributes to the language's expressive power.