Download presentation
Presentation is loading. Please wait.
1
JAVA Script : Functions Ashima Wadhwa
2
Function A group of statements that is put together (or defined) once and then can be used (by reference) repeatedly on a Web page Also known as subprogram, procedure, subroutine
3
Advantages of Functions
Number of lines of code is reduced Code becomes easier to read & understand Code becomes easier to maintain as changes need to be made only at a single location instead multiple locations
4
Function Identifiers The naming rules for function identifiers are the same as were discussed for variable and identifiers.
5
Creating JavaScript Functions
function function_name(parameters) { JavaScript commands } parameters are the values sent to the function (note: not all functions require parameters) { and } are used to mark the beginning and end of the commands in the function.
6
Creating JavaScript Functions
Function names are case-sensitive. The function name must begin with a letter or underscore ( _ ) and cannot contain any spaces. There is no limit to the number of function parameters that a function may contain. The parameters must be placed within parentheses, following the function name, and the parameters must be separated by commas.
7
Performing an Action with a Function
<html> <body> <button onclick="myFunction()">Try it</button> <script> function myFunction() { alert("Hello\nHow are you?"); } </script> </body> </html>
8
Returning a Value from a Function
To use a function to calculate a value use the return command along with a variable or value. function Area(Width, Length) { var Size = Width*Length; return Size; } the Area function calculates the area of a rectangular region and places the value in a variable named “Size” the value of the Size variable is returned by the function
9
Placing a Function in an HTML File
The function definition must be placed before the command that calls the function. One convention is to place all of the function definitions in the <head> section. A function is executed only when called by another JavaScript command. It’s common practice for JavaScript programmers to create libraries of functions located in external files.
10
Two Ways of Calling Functions
function popUp( message ) { window.alert( message ) ; } popUp( “Warning!” ) ; A function call appearing as a complete statement A function call appearing as part of a statement. Definitions of such functions include a ‘return’ statement function add( a, b ) { c = a + b ; return c ; } sum = add( 2, 4 ) ; document.write( sum ) ;
11
EXAMPLE 1 <html> <head> <script> function myFunction() { alert("Hello World!"); } </script> </head> <body> <button onclick="myFunction()">Try it</button> </body> </html>
12
EXAMPLE 2 <button onclick="myFunction('Harry Potter','Wizard')">Try it</button> <script> function myFunction(name,job) { alert("Welcome " + name + ", the " + job); } </script>
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.