Functions

In many programs we need to use the same piece of code again and again. It makes sense not to rewrite it, but to put that code in a special place, give it a name, and then use that name to call our code when needed. This is exactly how functions are declared and used in JavaScript.

Consider the following example:

<html>
<head>
<title>JavaScript Function Test</title>

<script type="text/javascript">
					function simpleFunction(x) {
					var y = "Your simple function says: " + x;
					return y
					}
					</script>

</head>
<body>

<script type="text/javascript">
					var aVar = "hi there!";
					document.write(simpleFunction(aVar))
					</script>

</body>
</html>

Not a very useful example of a function, but still, it demonstrates all the important points.

First, functions are normally declared in the <head> portion of an HTML page. As a result, they are guaranteed to be loaded into the memory before anything happens in the body. And there, in the body, the functions are normally used.

Our function accepts a parameter which is shown in its declaration as x. When calling the function, we pass it through this parameter some value, or some variable. The function, when called, performs some logic. And then, using the return statement, it sends back the result of its work. In our case, we are just printing the result onto the page.

Run this code in your browser and you should see:

Your simple function says: hi there!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset