Defining Functions

Here is a JavaScript function:

function total(x, y) {
  return x + y;
}

It is, in many ways, similar to functions in languages like Java and C++:

  • A function can take zero or more named parameters.
  • A function groups several statements (in the function body).
  • A function creates scope: variables declared in a function are local to that function (even when declared with the var keyword).
  • A function can return a value (using the return statement).
  • A return statement terminates the function immediately.

JavaScript functions are different in several ways from functions in Java and C++. The most visible difference (besides using the function keyword) is the lack of types; there are no parameter or return types.

Moreover, JavaScript functions always return a value! If a function terminates without explicitly returning a value, it returns undefined.

However, the most critical difference is that JavaScript functions are values (actually, they are [special] objects). Thus, you can store functions in variables. You can also pass them as arguments to other functions or return a function from another function.

Terminology: A higher order function is a function that takes a function as an argument or returns a function.

In contrast, first-order functions don't take a function as an argument (nor do they return a function as output).

JavaScript supports both first and higher-order functions.

Calling Functions

To invoke a JavaScript function, call its name followed by a pair of parentheses with zero or more arguments.

const result = add(2, 1); 

When using a function as a value, use its name without parentheses/arguments.

const sum = add;
// you can use sum as an alias to add
// e.g. const result = sum (2, 1)