Functions - More than One Way of Doing It

As with so many things in programming, there is more than one way of doing it. Functions may be defined in one of several ways. Let us see

Example 4.2. Function Definition

aka function declaration, or function statement.

function diff(a, b) {
    return a - b;
}

Example 4.3. Function Expression 1

This defines an anonymous function and assigns it to a variable diff1. De facto name of function diff1.

let diff1 = function(a, b) {
    return a - b;
}

Example 4.4. Function Expression 1a

An anonymous function assigned to a constant. De facto name of function diff2.

const diff2 = function(a, b) {
    return a - b;
}

Example 4.5. Anonymous Arrow Function

Here we create an anonymous function without using the function keyword, in stead we use => (arrow).

const diff3 = (a, b) => {
    return a - b;
}

For almost all practical purposes these definitions are equivalent. The latter three prove that a function is a value that may be assigned to a variable. The former three all use the function keyword making human reading easier.