Javascript Function

 Chapter 5:Function


Understanding Functions


A Javascript function is simply a script that is sectioned off as a separate piece of code and given a name. Using this name, a script can then call this separate script to execute at any time and as often as it needs. Many programming languages such  as C and C++ also use functions, whereas others incorporate the same tools but call them procedures or subroutines. They all do basically the same thing, but they do have their differences.


Functions are meant to serve a single purpose to help split up the many tasks that one scripts is designed to do. Functions can receive values from their calling statements, called arguments. You can then use the data that is received within the statement block as variables.


Creating Functions


Syntax


function functionName([argument1] [argumentN])

{

[statement]

[return]

}


The keyword function is used to specify a name, functionName , which serves as the identifier for the set of statements between the curly braces. Enclosed in parentheses and separated by commas are the argument names that hold each hold each value that a function receives. Technically, arguments are variables that are assigned to literal values, other variables, or objects that are passed to the function by calling statement. If you do not specify any arguments, you must still include an empty set of parentheses to complete the declaration. The statements which are the core of the function, are executed each time the function is called. For better readability , statements within the statement block are typically indented.


Where to Declare Functions


You can declare functions anywhere inside a <script> block except within other functions or control structures. Keep in mind that just as different blocks of an HTML document are loaded ahead of others, so are any scripts that are embedded in these blocks. For this reason, it is recommended that you declare functions inside a script that is embedded in the <head> block of a document. Declaring all your functions here ensures that the functions are available if another script needs to use them immediately.


Calling Functions


You can call the function as given below.

[variable=] Function_name([values])


Working with Arguments


Setting up functions to accept arguments can be very useful. For example, you might want to create a function to be used many times throughout your program; however , you can encounter different issues when reusing the function. One of the values inside the function might need to change each time it is used. One way to solve this problem is to use global variable that can be modified both outside and inside the function. This can get confusing if you typically use the same variable names inside different functions. The best thing to do is set up the function  to accept an argument for each value you want it to receive.


Reusing Functions


Functions are great for separating an application into its logical parts, but their best advantage is promoting the reuse of code. Functions are unlike sections of code enclosed in loops to be repeated many times in succession; You can reuse a function at any given time by simply calling its name.


Examples


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Function</title>


    <script>

       function factorial()

       {

        fact=1

        no=parseInt(prompt("Enter a number to find Factorial",0))

        for(i=1;i<=no;i++)

        {

            fact*=i

        }

        alert("The factorial is:"+fact);

       }

        </script>

        </head>

        <body>

            <script>

                factorial();

                </script>

</body>

</html>



Output

fun.PNG

fun1.PNG


Recursive Functions


Javascript functions can be recursive, which means that a function can call itself . Solving factorial equations is a common way to demonstrate how recursion works , so I included an example here. To find the factorial of any positive integer n , you simply find the product of all integers 1 through n. To find the factorial of 6, written 6!, you calculate the following:


6!= 6 x 5 x 4 x 3 x 2 x1 = 720


To calculate 7!, you would use the following:


7!= 7 x 6 x 5 x 4 x 3 x 2 x 1

Comparing these two calculations, you can produce a general formula to use in your function. Notice that 7! Is equal to 7 x 6!. For any positive integer n greater than 0,

n !=nx(n-1)!

The first iteration of this would look like this:

7 !=7 x (7-1) !

=7 x 6!

From here , you have to stop and calculate 6! Before continuing with the rest of the calculation. This occurs six more times before you can back out of each one and find the final solution. Instead of doing that , you can use a recursive function such as the following:


Function getFactorial(n)

{

Var result

If(n>0)

Result=n*getFactorial(n-1)

else if(n==0)

result=1

else result =null

return (result)


The function first checks to see if n is greater than 0 , which happens the majority of the time. If this is true, the function multiplies n by the result returned by calling the function again with a different argument-in this case, n-1. This continues to put many getFactorial functions on hold until n is equal to zero. At this point , the most nested occurrence of the function finishes and returns the first value. Javascript then backs out and finishes each nested function until it reaches the first value. Javascript then backs out and finishes each nested function until it reaches the original call to getFactorial and returns the final result.


No comments:

Post a Comment