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

Function Topic

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