Java Functions
Exploring Functions
Defining and Invoking a Function
Defining Function arguments
Defining a Return Statement
Defining Function Scope and Closures
Calling Functions with Timer
1
JavaScript Functions
A JavaScript function is a block of code designed to perform a
particular task.
A JavaScript function is executed when “something” invokes it(calls it).
We can also use functions to perform repetitive tasks, such as
displaying a message whenever web page loads a browser.
In JavaScript, functions are placed under the head and body sections
of HTML document.
The JavaScript functions are divided into two categories:
Function with parameters
Function without parameters
Built-in global functions of JavaScript
Function Description
alert() Displays information in a message box. This function
displays an error message when you validate a form
prompt() Displays a message box consisting of the OK and
Cancel buttons. This function returns a text string when
the OK button is clicked and null when the cancel
button is clicked
confirm() Displays a message box with two buttons, OK and
Cancel. When you click the OK button, the function
returns true. When you click the cancel button, the
function returns false.
eval() Evaluates and executes a string and returns a result
2
isFinite() Returns a Boolean value, true or false, indicating
whether the argument passed to it is finite or infinite.
isNaN() Determines whether or not a value is an illegal number.
NaN stands for Not a Number
parseInt() Extracts a number from the beginning of a string. This
function parses the string and returns the first integer
value found in the string
parseFloat() Extracts a number from the beginning of a string. The
function parses the string and returns the first floating-
point value found in the string.
Number() Converts a value of an object into a number. If the
object contains Boolean value, then it returns 1 for true
and 0 for false
escape() Encodes a string so that it can be transmitted across
any network to any computer that supports ASCII
characters. This function encodes special characters
except *,@,-,_,+and /.
unescape() Decodes a string that is encoded by the escape()
function
3
Defining and invoking a function
A function contains code that is executed when an event is triggerd or
the function is called.
A JavaScript function is defined with the function keyword, followed by
a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar
signs (same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly
brackets: {}
Example:
function function_name( parameter1,parameter2,…….)
{
//code to be executed
}
Defining function arguments
Arguments are the values passed to the function while calling it.
It is important to note that the number and order of arguments passed in the function
call should match with the number and order of arguments that we define in the
function
When a function called, the block of code inside the function is executed.
Syntax:
Function_name(arg1,arg2…..)
Defining a return statement
A return statement specifies the value that is returned from a function
return statement can be used anywhere in the function
The execution of a return statement is the final act of a function
Syntax:
return value;
4
Example program:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>This example calls a function which performs a calculation, and
returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2)//function with parameters
{
return p1 * p2; //using return statement
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>
Output:
5
Defining function scope and closures
A scope refers to on area within a function and its variables are
accessible.
In JavaScript, scope of a function is divided into Global and Local
Global: specifies that a function can be called or accessed from
anywhere in a program
Local: specifies that a function can be accessed only within its parent
function
CLOSURE: It is a variable that is created inside a function and
continues to exist after the function has finished executing.
Closures are used in defining control structures, such as branches and
loops.
Program:
<!DOCTYPE html>
<html>
<body>
<p>A function can access variables defined inside the function:</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<p id="demo"></p>
<script>
myFunction();
function myFunction() {
var a = 4;
add();
function add()
{
document.getElementById("demo").innerHTML = a + a;
}}
</script></body></html>
6
Output:
Calling function with Timers
Timer is one of the most important feature of JavaScript, which allows
you to execute JavaScript function only after a specified period of time.
To use timers JavaScript provides various methods.
1. The setTimeout() method: executes code at a specified interval.
Syntax: setTimeout(function,delayTime)
Function parameter specifies the method that the timer calls and the
delayTime parameter specifies the number of milliseconds to wait before
calling the method.
Program:
<!DOCTYPE HTML>
<HEAD>
<SCRIPT TYPE+"textjavascript">
function timedMsg()
{
var t=setTimeout("alert('5 seconds!')",5000);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<INPUT type="button" value="timed alert box!"
onclick="timedMsg()"/>
7
</FORM>
</BODY>
</HTML>
Output:
2. The clearTimeout() method: deactivates or cancels the timer that is
set using the setTimeout() method.
Syntax: clearTimeout(timer)
The parameter timer is a variabe that is created using the setTimeout()
method.
3. The setInterval() method: executes a function after a specified time
interval.
Syntax: setInterval(function,intervalTime)
Function parameter specifies the method to be called; whereas the
intervalTime parameter specifies the time interval between the
functioncalls.
Program:
<!DOCTYPE HTML>
<HEAD>
<SCRIPT type="text/javascript">
function timedMsg()
{
var t=setInterval("alert('1seconds!')",1000);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
8
<INPUT type="button" value="timed alert box!" onclick="timedMsg()"/>
</FORM>
</BODY>
</HTML>
Output:
4. The clearInterval() method: deactivates or cancels the timer that is
set using the clearInterval() method.
Syntax: clearInterval(timer)
the parameter timer is a variable that is created using the setInterval()
method.