JS: Define Function

By Xah Lee. Date: . Last updated: .

Create a Function

There are 3 ways to create a function.

  1. By the keyword function.
  2. By Arrow Function. Most simple.
  3. By Function Constructor keyword Function.

Keyword “function”

The syntax is:

function name (parameters) {body_statements}

Return Statement

In the function body, you can have 0 or more return expr.

When program reaches the return statement, it'll exit the function, and return the value.

Function without return statement returns the value undefined.

function ff(x) {
  return x + 1;
}

console.log(ff(2));
// 3

JavaScript, Function