JavaScript Function()
The Function() Constructor
The Function() constructor creates function objects.
Functions are executable blocks of code.
In JavaScript, functions are objects.
All JavaScript constructors, like Object(),
Array(), and Date(), are Function objects.
Syntax
Function(arg1, body)
Function(arg1, arg2, ..., argN, body)
new Function(body)
new Function(arg1, arg2, ..., argN, body)
Parameters
| Parameter | Description |
|---|---|
| arg1, arg2, ..., argN | Optional. Names of the function parameters. |
| body | A string containing the function body. |
Return Value
| Call | Returns |
|---|---|
Function(...) |
A Function object |
new Function(...) |
A Function object |
Creating a Function
Example
sum(5, 3) // 8;
Function Declaration (Recommended)
Function declarations and function expressions are usually preferred over the Function constructor.
Example
return a + b;
}
Avoid using the Function() constructor unless you need to create functions dynamically.
Function declarations and function expressions are usually easier to read and maintain.
Functions Are Objects
Functions are objects.
Functions can be assigned to variables, passed as arguments, and returned from other functions.
Example
return "Hello";
}
(typeof greet) // function
Constructors Are Functions
JavaScript constructors are Function objects.
Example
(typeof Object) // function
(typeof Array) // function
(typeof Date) // function
Object Hierarchy
The Function constructor inherits from Object.
Object └─ Function ├─ Array ├─ String ├─ Number ├─ Boolean ├─ Date ├─ RegExp ├─ Error ├─ Map ├─ Set └─ Promise └─ Custom Objects
Every constructor in this tutorial is itself a Function object:
typeof String // "function"
typeof RegExp // "function"
typeof Object // "function"
String instanceof Function // true
Object instanceof Function // true
Common Function Properties and Methods
lengthnamecall()apply()bind()
Browser Support
Function() is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera |