JavaScript: Define Function

By Xah Lee. Date: . Last updated: .

There are 3 ways to create a function.

  1. By Arrow Function expression. (JS2015)
  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.

Example:

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

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

[see 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.

Define Function by Constructor

Function Constructor

JavaScript Function

BUY
Ξ£JS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc