JS: Define Function

By Xah Lee. Date: . Last updated: .

There are 3 ways to create a function.

  1. By Arrow Function expression. (ES2015)
  2. By the keyword function. Either as expression or as declaration.
  3. By constructor with keyword Function. (good for creating function at run-time.)

Arrow Function

Arrow function is the most simple and useful.

Examples:

((x,y) => x + y)

((x,y) => {return x + y})

Arrow function is a expression. It returns a value that represents the function. You can give it a name by assigning it to a variable.

[see JS: Arrow 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 Declaration

When you have this:

function name (…) {…}

at top-level of source code (e.g. not inside any curly bracket), or top-level inside a function, it is called Function Declaration. (Otherwise it's Function Expression.)

Function Declaration is the most common way to define a function.

function f() { return 3; }
console.log(
    f()
); // 3

function g(x) { return x; }
console.log(
    g(2)
); // 2

function h(x,y) { return x+y; }
console.log(
    h(3,4)
); // prints 2

Function Expression

When you have this:

function name (…) {…}

or

function (…) {…}

and it is not at top-level of source code, nor at top-level inside a function, it is called Function Expression.

// function expression, applied on the spot
console.log(
    (function () { return 3; })()
); // prints 3
// function expression with one parameter, applied on the spot
console.log(
    (function (x) { return x; })(4)
); // prints 4

You can assign a function to a variable. In effect, giving the function a name.

// function expression, assigned to a variable
const g = function () { return 3; };
console.log(g()); // prints 3

Function Declaration vs Function Expression

JS: Function Declaration vs Function Expression

Define Function by Constructor

JS: Function Constructor

JS Function

  1. Define Function
  2. Arrow Function ⭐
  3. Function Params
  4. “arguments” Object
  5. Rest Params ⭐
  6. Arg Default Value ⭐
  7. Arg Destructure ⭐
  8. f Declaration vs Expression
  9. Closure
  10. f call apply bind
  11. Functional Programing
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog