Did you find this useful?
Socialize it today.


JavaScript Functions

Wednesday, April 11, 2012

JavaScript is normally executed when the page loads. To prevent this from happening, you can place your JavaScript code within a function. To execute the JavaScript code, you must call the function. Functions can be called from anywhere in the webpage. Functions can also exist outside of the page within an external JavaScript file. Functions can be located within both in the <head> and/or the <body> elements within a webpage. However, to ensure that functions are available when they are called, they should be placed within the <head> element so they are downloaded by the browser prior to the page's content.


JavaScript Function

Here is an example of the syntax for a function.


function functionName(variable#1, variable#2, etc..)
{
JavaScript Code
}


In the example above, the parameters variable#1, variable#2, etc. are variables that are passed into the function. The braces define the start and end of the function. If the function does not require any parameters, you still need to include the parenthesis after the name of the function. In addition, as we discussed in a previous article, JavaScript is case sensitive. The keyword function, must be in lowercase. Let's take a look at an example of how this would be implemented within a webpage.


<html>
<head>
<script type="text/javascript">
function displayalert()
{
alert("Hello World!");
}
</script>
</head>

<body>
<form>
<input type="button" value="Click Here" onclick="displayalert()" />
</form>
</body>
</html>


Since the JavaScript statement "alert("Hello World!")" is within a function, it will not execute during the page load.  It will only execute when the function is called from within the page.  In this example, we call the function by clicking on the input button located in the <body> element.


Return Statement

JavaScript, like other programming languages, has the ability to return data back from a function. This is very useful where you have a need to send data to a function, perform a calculation, then return the results back to the object that made the call to the function. The return statement is used for this purpose. Here is an example on how to use the return statement within a function.


<html>
<head>
<script type="text/javascript">
function addTwoNum(x,y)
{
return x+y;
}
</script>
</head>

<body>
<form>
<input type="button" value="Add 2+3" onclick="alert(addTwoNum(2,3));" />
</form>
</body>
</html>

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

Professional JavaScript for Web Developers JavaScript and jQuery: The Missing Manual HTML CSS and JavaScript Editor