JavaScript Function Object

In JavaScript, functions are called Function Objects because they are objects.

In JavaScript, the purpose of Function constructor is to create a new Function object. 

Just like objects, functions have properties and methods, they can be stored in a variable or an array, and be passed as arguments to other functions.

Syntax

As all other objects, Function objects can be created using the new operator as shown below.

new Function ([arg1[, arg2[, ....argn]],] functionBody)

arg1, arg2, …. , argn – It represents the argument used by function. Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.

functionBody – It represents the function definition. A string containing the JavaScript statements comprising the function body.

Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

Example

<script>  
var add=new Function("num1","num2","return num1+num2");  
document.writeln(add(2,5));  //Output will be 7
</script>  

Function Properties

Javascript Function.length: Returns the number of parameters of a function.

Javascript Function.name: Returns the name of the given function.

Function Methods

MethodDescription
apply()It is used to call a function contains this value and a single array of arguments.
bind()It is used to create a new function.
call()It is used to call a function contains this value and an argument list.
toString()It returns the result in a form of a string.
Function Methods