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 assign it to a variable to give the function a name.

[see JS: Arrow Function]

Keyword 「function」

The keyword function lets you define a function. The syntax is:

function name(…) {…}

or without a name.

function (…) {…}

Its value represents a function.

Function as Expression

You can create a function without a name.

// 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

Tip: you can always use this form const name = function (…) {…}; to define all your functions. The advantage is that you don't have name hoisting complexity, and can have function inside function or curly brace blocks. [see JS: Function Declaration vs Function Expression]

Define Function by Declaration

The most common and practical way is by function declaration.

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

Define Function by Constructor

[see JS: Function Constructor]

Function Topic

  1. JS: Define Function
  2. JS: Arrow Function
  3. JS: Function Parameters
  4. JS: var/function Declaration Order
  5. JS: var Name Scope
  6. JS: Function Declaration vs Function Expression
  7. JS: Closure
  8. JS: Functional Programing
  9. JS: Function Call, Apply, Bind
  10. JS: Function Argument Default Value
  11. JS: Function Rest Parameters
  12. JS: Function Argument Destructure

  1. JS: Function Object
  2. JS: Function.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon