Functions
Function declarations

A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by:

  • The name of the function.
  • A list of arguments to the function, enclosed in parentheses and separated by commas.
  • The JavaScript statements that define the function, enclosed in curly brackets, { }.

For example, the following code defines a simple function named square:

function square(number) { return number * number; }

The function square takes one argument, called number. The function consists of one statement that says to return the argument of the function (that is, number) multiplied by itself. The return statement specifies the value returned by the function.

return number * number;

Primitive parameters (such as a number) are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

Defining functions

JS has 4 kinds of functions:

  • Regular function: can return anything; always runs to completion after invocation.
  • Generator function: returns a Generator object; can be paused and resumed with the yield operator
  • Async function: returns a Promise; can be paused and resumed with the await operator
  • Async generator function: returns an AsyncGenerator object; both the await and yield operators can be used

Classes are conceptually not functions (because they throw an error when called without new), but they also inherit from Function.prototype and have typeof MyClass === "function".

// Constructor
const multiply = new Function("x", "y", "return x * y");

// Declaration
function multiply(x, y) {
    return x * y;
}

// Expression; the function is anonymous but assigned to a variable
const multiply = function (x, y) {
    return x * y;
};

// Expression; the function has its own name
const multiply = function funcName(x, y) {
    return x * y;
};
                    
// Arrow function
const multiply = (x, y) => x * y;
                    
// Method
const obj = {
    multiply(x, y) {
        return x * y;
    },
};