JavaScript Function()
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(body)
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
const sum = new Function("a", "b", "return a + b");
sum(5, 3) // 8;
Function Declaration (Recommended)
Function declarations and function expressions are usually preferred over the Function constructor.
Example
function sum(a, b) {
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
function greet() {
return "Hello";
}
(typeof greet) // function
Constructors Are Functions
JavaScript constructors are Function objects.
Example
document.getElementById("demo").innerHTML =
(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
| Constructor Type | Function |
| Creates | Function objects |
| Inherits From | Object |
Every constructor in this tutorial is itself a Function object:
typeof Array // "function"
typeof String // "function"
typeof RegExp // "function"
typeof Object // "function"
Array instanceof Function // true
String instanceof Function // true
Object instanceof Function // true
Common Function Properties and Methods
lengthnamecall()apply()bind()
Browser Support
new Function() is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera |