Part-3
The prepackaged functions that belong to JavaScript objects such as
Math.pow, are called methods.
You can write functions to define tasks that may be used at many
points in a script. These are referred to as programmer-defined
functions.
The actual statements defining the function are written only once
and are hidden from other functions.
A function is invoked by a function call.
The function call specifies the function name and provides
information (as arguments) that the called function needs to
perform its task
A boss (the calling function, or caller) asks a worker
(the called function) to perform a task and return (i.e., report
back) the results when the task is done.
Function definition
function function-name( parameter-list )
{
declarations and statements
}
<head>
<script type=“text/javascript”>
document.writeln( "<h1>Square the numbers
from 1 to 10</h1>" );
for ( var x = 1; x <= 10; ++x )
document.writeln( "The square of " + x + " is "
+ square( x ) );
function square( y )
{
return y * y;
}
</script>
</head>
Function square uses this name in its body to
manipulate the value passed to square from
the function call.
The return statement in square passes the
result of the calculation y * y back to the
calling function.
The function-name is any valid identifier. The parameter-list
is a comma-separated list containing the names of the
parameters received by the function when it’s called.
There should be one argument in the function call for each
parameter in the function definition.
The declarations and statements between the
braces form the function body.
If the function doesnot return a result use : return;
If the function returns a result use : return(expression);
<head>
<script type=“text/javascript”>
var input1 = window.prompt( "Enter first number", "0" );
var input2 = window.prompt( "Enter second number", "0" );
var input3 = window.prompt( "Enter third number", "0" );
var value1 = parseFloat( input1 );
var value2 = parseFloat( input2 );
var value3 = parseFloat( input3 );
var maxValue = maximum( value1, value2, value3 );
document.write(“Maximum is” +maxValue);
function maximum( x, y, z )
{
return Math.max( x, Math.max( y, z ) );
}
</script>
</head>
There are several reasons for modularizing a program with
functions.
The divide-and conquer approach makes program
development more manageable.
Another reason is software reusability (i.e., using existing
functions as building blocks to create new programs).
With good function naming and definition, significant
portions of programs can be created from standardized
functions rather than built by using customized code.
A third reason is to avoid repeating code in a program.
1.var random_Value = Math.random();
Method random generates a floating-point value from 0.0 up to,
but not including, 1.0
2.Math.floor( 1 + Math.random() * 6 )
The scope of an identifier for a variable or function is the portion of
the program in which the identifier can be referenced.
Global variables or script-level variables that are declared in the head
element are accessible in any part of a script and are said to have global
scope.
Thus every function in the page’s script(s) can potentially use the
variables.
Identifiers declared inside a function have function (or local) scope and
can be used only in that function.
Function scope begins with the opening left brace ({) of the function in
which the identifier is declared and ends at the function’s terminating right
brace (}).
Local variables of a function and function parameters have function scope.
If a local variable in a function has the same name as a global
variable, the global variable is “hidden” from the body of the
function.
<head>
<script type=“text/javascript”>
var output;
var x = 1;
function start()
{
var x = 5; // variable local to function start
document.writeln( "<p>local x in start is " + x +
"</p>“);
functionA(); // functionA has local x
functionB(); // functionB uses global variable x
document.writeln( “local x in start is " + x );
}
function functionA()
{
var x = 25; // initialized each time functionA is called
document.writeln“local x in functionA is " + x +" after entering functionA“);
++x;
document.writeln( "local x in functionA is " + x +" before exiting
functionA “);
}
function functionB()
{
document.writeln( “global variable x is " + x +" on entering
functionB“);
x *= 10;
document.writeln( "global variable x is " + x + " on exiting
functionB“);
}
</script>
</head>
local x in start is 5
local x in functionA is 25 after entering functionA
local x in functionA is 26 before exiting
functionA
global variable x is 1 on entering functionB
global variable x is 10 on exiting functionB
local x in start is 5
parseInt(), parseFloat()
(e.g)parseInt(“123abc”) returns the integer value 123
isFinite() returns TRUE if the argument is not a NaN,
Number.POSITIVE_INFINITY
isNaN() takes a numeric argument and returns TRUE if the
value of the argument is not a number.
A recursive function is a function that calls
itself, either directly, or indirectly through another function.
Recursive problem-solving approaches have a number of
elements in common.
A recursive function is called to solve a problem.
The function actually knows how to solve only the simplest
case(s), or base case(s).
If the function is called with a base case, the function
returns a result.
If the function is called with a more complex problem, it
divides the problem into two conceptual pieces—a piece that
the function knows how to process (the base case) and a piece
that the function does not know how to process.
The function invokes (calls) a fresh copy of itself to go to
work on the smaller problem; this invocation is referred to as
a recursive call, or the recursion step.
(e.g)
<script>
var output= “ “;
function calfactorial()
{
for(var i=0;i<=10;i++)
document.write( i + ”! =” +factorial(i));
}
function factorial(number)
{
if(number<=1)
return 1;
else
return number*factorial(number-1);
}
</script>
Both iteration and recursion are based on a control statement:
Iteration uses a repetition statement (e.g., for, while or do…
while); recursion uses a selection statement (e.g.,if, if…else or
switch).
Both iteration and recursion involve repetition: Iteration
explicitly uses a repetition statement; recursion achieves
repetition through repeated function calls.
Iteration and recursion each involve a termination test:
Iteration terminates when the loop-continuation condition
fails; recursion terminates when a base case is recognized.
Iteration both with counter-controlled repetition and with
recursion gradually approaches termination
Iteration keeps modifying a counter until the counter assumes
a value that makes the loop-continuation condition fail;
recursion keeps producing simpler versions of the original
problem until the base case is reached.
Both iteration and recursion can occur infinitely.
An infinite loop occurs with iteration if the loop-continuation
test never becomes false; infinite recursion occurs if the
recursion step does not reduce the problem each time via a
sequence that converges on the base case or if the base case is
incorrect.
We can pass a function as an argument to a function.
This function that is passed as an argument inside of
another function is called a callback function
A callback is a function that is passed as an
ar.gument to another function, and is called after the
main function has finished its execution.
The main function is called with a callback function
as its argument, and when the main function is
finished, it calls the callback function to provide a
result.
function myDisplayer(sum)
{
document.writeln(“Sum is “+sum);
}
function myCalculator(num1, num2, myCallback)
{
var sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
Callbacks allow you to handle the results of an
asynchronous operation in a non-blocking manner,
which means that the program can continue to run
while the operation is being executed.