Home >>Javascript Tutorial >JavaScript Function
Functions in JavaScript are used to execute operations. JavaScript functions can be called multiple times in order to reuse the code.
Let's get to know the advantages of JavaScript functions:
Mainly there are 3 advantages of JavaScript functions.
The syntax for declaring a function is displayed below:
function functionName([arg1, arg2, ...argN]) { //code to be executed }
Please note that JavaScript functions can have zero or more arguments.
Let's take an example to understand the JavaScript Function that doesn't contain any arguments.
<html> <head> <title>JavaScript Function</title> <script> function msg() { alert("Welcome to PHPTPOINT"); } </script> </head> <body> <input type="button" onclick="msg()" value="Welcome"/> </body> </html>
A function can be called in JavaScript by passing Arguments. Here is one example of a JavaScript Function containing one argument.
<html> <head> <title>JavaScript Function</title> <script> function getcube(Integer) { alert(Integer* Integer * Integer); } </script> </head> <body> <input type="button" value="get value" onclick="getcube(6)"/> </body> </html>
Here, we can use the value returned by the function and it can be used in the program. Here is one example of a JavaScript Function that returns a value.
<html> <head> <title>JavaScript Function</title> </head> <body> <script> function getInfo() { return "Hello PHPTPOINT! How are Things?"; } document.write(getInfo()); </script> </body> </html>
The main motive of Function Constructor in JavaScript is creating a new Function object that executes the code globally.
A function is created dynamically in an unsecured way, if the constructor is called directly.
Here is the Syntax
new Function ([arg1[, arg2[, ....argn]],] functionBody)
Here are the Parameters
arg1, arg2, .... , argn – these represents the argument used by the function.
functionBody - It depicts the definition of the function.
Method | Description |
---|---|
apply() | In order to call a function that contains this value and a single array of arguments. |
bind() | In order to create a new function this method is used. |
call() | In order to call a function that contains this value and an argument list. |
toString() | This returns the result in the form of a string. |
<script> var add=new Function("num1","num2","return num1+num2"); document.writeln(add(5,25)); </script>The output of the above mentioned example is 30.
<script> var pow=new Function("num1","num2","return Math.pow(num1,num2)"); document.writeln(pow(5,3)); </script>The output of the above mentioned example is 125.