Different Ways to Write Functions in JavaScript

  1. Function Declaration

    function add(a, b) {
      return a + b;
    }
    console.log(add(2, 3)); // Output: 5

    Explanation: This is the classic way to define a function. It can be called before it appears in the code (hoisted).

  2. Function Expression

    const multiply = function(a, b) {
      return a * b;
    };
    console.log(multiply(2, 3)); // Output: 6

    Explanation: The function is stored in a variable. It is not hoisted, so it must be defined before use.

  3. Named Function Expression

    const divide = function divideFunc(a, b) {
      return a / b;
    };
    console.log(divide(6, 2)); // Output: 3

    Explanation: Similar to a function expression, but the function has its own name (useful for recursion or debugging).

  4. Arrow Function

    const subtract = (a, b) => a - b;
    console.log(subtract(5, 2)); // Output: 3

    Explanation: Shorter syntax, does not have its own this context.

  5. Arrow Function with One Parameter

    const square = x => x * x;
    console.log(square(4)); // Output: 16

    Explanation: Parentheses can be omitted if there is only one parameter.

  6. Function as a Method (Object)

    const calculator = {
      sum: function(a, b) {
        return a + b;
      }
    };
    console.log(calculator.sum(3, 4)); // Output: 7

    Explanation: Functions can be properties (methods) of objects.

  7. Shorthand Method Syntax (ES6)

    const math = {
      multiply(a, b) {
        return a * b;
      }
    };
    console.log(math.multiply(3, 5)); // Output: 15

    Explanation: ES6 allows a shorter way to define methods in objects.

  8. Constructor Function

    function Person(name) {
      this.name = name;
    }
    const person1 = new Person('Alice');
    console.log(person1.name); // Output: Alice

    Explanation: Used to create objects with the new keyword.

  9. Immediately Invoked Function Expression (IIFE)

    (function() {
      console.log('IIFE runs immediately!');
    })();

    Explanation: Runs as soon as it is defined. Useful for creating a private scope.