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.


((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; }
); // 3

function g(x) { return x; }
); // 2

function h(x,y) { return x+y; }
); // prints 2

Function Expression

When you have this:

function name (…) {…}


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
    (function () { return 3; })()
); // prints 3
// function expression with one parameter, applied on the spot
    (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

Function Topic

  1. Define Function
  2. Functional Programing
  3. Arrow Function
  4. Function Parameters
  5. f Declaration vs Expression
  6. Closure
  7. Function Call, Apply, Bind
  8. Function Argument Default Value
  9. Function Rest Parameters
  10. Function Argument Destructure
  11. Function Object
  12. Function.prototype
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 Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc