Lesson 5 continued:


The code explained:


function x(a,b) {

z=a+b;

document.write(z);>br> }


On the first line we used the function key word to declare our function and then we named our function: x and gave it two arguments: (a,b) and finally on line one, we use the { to begin the functions code. On line two we declare a new variable: z and make it equal to the sum of a+b. On the 3rd line we introduce a new Method, the write method. This method is used to write HTML expressions to the specified document. We told it to write the variable z to the page and variable z is the sum of a and b so I will explain what the result of z will be after we explain the rest of the html page which is:


<form>

<input type="button" value="push" onClick="x(2,3)">

</form>


Okay, you should be familiar with the <form> and </form> tags and probably even the button itself if you have studied html forms. Lets break down the second line of code for those of you that are not yet familliar with forms and javascript together: first we declare an input type as button and assign the value of "push" so the result of that is a buttonn on our page that says push o n it. Next we add something new, The OnClick event. The onClick event will be covered in a later lesson. For now all we need to know is that it tells the browser to call the function when the button is clicked. Next you will notice that we have passed two arguments to the x function (2,3). This sets the values of (a,b) respectively to (2,3). It makes a=2 and b=3. So in line 2 of our function, z=a+b. So now z=2+3 or z = 5. Now line 3 prints z or 5 to the page! Got it? Try to type the entire page yourself and run it in your browser and it will give you a better perpective when you do it yourself.


The function call:
The function is nothing but a data container and will do nothing until it is called. In the above example, the function is called by using a button and the OnClick event. Here we will demonstrate the simplest way to make a function call:

Inside our script tags we would simply place the function call where we want the results displayed:


<html>

<head>

<title>Code Template</title>

<script type="text/javascript">

<!--

function x(a,b) {

z=a+b;

document.write(z);

}


//-->

</script>

</head>

<body>


<script type="text/javascript">

<!--

x(3,4)

//
-->

</script>

</body>

</html>


This will result in just the number 7 being printed to the page.


Okay, now you know how to create a basic function and call it. Now let's look at some of JavaScript's built in functions in Lessons 6,7 and 8.

                    

Copyright © 2012 VisualBuilder. All rights reserved