Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 77 - 2609_Logicode
P. 77

    FUNCTIONS IN JAVASCRIPT

                     A block of code created specifically to carry out a specific task is referred to as a JavaScript
                     function. When a JavaScript function is called, it is executed.

                     CREATING AND CALLING A FUNCTION
                     Defining a function in JavaScript involves several key elements that determine the functionality of
                     the function and how it may be utilised.

                     The syntax of creating a function is as follows:

                     function name (parameter1, parameter2, parameter3,...,parameterN)
                     {

                     // code to be executed
                     }

                     To execute the function and pass an argument to the parameter, we invoke it by its name and
                     pass an argument (value).

                     The syntax of calling a function is as follows:

                     function name (argument1, argument2, ...); //invoking the function
                     For example,

                     function hello (name)
                     {

                     document.write("Hello, " + name + "!");

                     }
                     hello("JavaScript");

                     The output of the preceding program is as follows:

                     Hello, JavaScript!
                     In this example, hello is the function name, name is a parameter, which is used inside the function
                     to greet a person. The function uses document.write() to output a message.

                     To execute  the function  and pass  the argument value
                     “JavaScript”, we call the function as hello(“JavaScript”);.

                        Code
                          5       Create a web page to demonstrate the use of functions in JavaScript.

                     <!DOCTYPE HTML>

                     <HTML>
                     <HEAD>

                                                                                               JavaScript for Beginners  75

| 72 73 74 75 76 77 78 79 80 81 82 |