Sobes.tech
Junior

What ways of creating functions do you know?

sobes.tech AI

Answer from AI

  1. Function Declaration

    // Function definition
    function greet(name) {
      return `Hello, ${name}!`;
    }
    

    Functions declared this way are available before the line where they are declared (hoisting).

  2. Function Expression

    // Assigning an anonymous function to a variable
    const greet = function(name) {
      return `Hello, ${name}!`;
    };
    

    The function is created at runtime, hoisting does not apply to the variable holding the function. It can be named or anonymous.

  3. Arrow Function

    // Concise function syntax
    const greet = (name) => {
      return `Hello, ${name}!`;
    };
    
    // For a single parameter, parentheses can be omitted
    const greet = name => {
      return `Hello, ${name}!`;
    };
    
    // If the function body consists of a single return, parentheses and return can be omitted
    const greet = name => `Hello, ${name}!`;
    

    Arrow functions lexically bind this, do not have their own arguments. They cannot be used as constructors.

  4. Function Constructor

    // Using the Function constructor
    const greet = new Function('name', 'return "Hello, " + name + "!";');
    

    Functions are created dynamically from a string. Not recommended for regular use due to performance issues (double parsing) and security concerns (similar to eval).

  5. Object Methods

    // Function as an object property
    const person = {
      name: 'Ivan',
      greet: function() { // Function Expression as a method
        return `Hello, ${this.name}!`;
      },
      sayHello() { // Concise method syntax (ES6)
        return `Hello, ${this.name}!`;
      }
    };
    

    Functions defined as object properties. The concise syntax (sayHello()) is syntactic sugar for sayHello: function().

  6. Generator Function

    // A function that can pause and resume execution
    function* generateNumbers() {
      yield 1;
      yield 2;
      yield 3;
    }
    

    Uses yield to return intermediate values and create iterators. Defined with the syntax function*.

  7. Async Functions

    // Function working with promises
    async function fetchData() {
      const response = await fetch('...');
      const data = await response.json();
      return data;
    }
    

    Simplifies working with asynchronous code, allowing the use of await to wait for promises in a non-blocking manner. Defined with the syntax async function.