English
German

Javascript Functions

JavaScript Functions

If you have any programming experience, you do not need to spend much time on this lesson. Functions in JavaScript behave similarly to numerous programming languages (C, C++, PHP, etc). If this is your first time learning about functions, then be sure to go through this lesson very thoroughly. A solid understanding of functions will make the rest of this tutorial much easier to follow.


What is a Function

A function is a piece of code that sits dormant until it is referenced or called upon to do its "function". In addition to controllable execution, functions are also a great time saver for doing repetitive tasks.

Instead of having to type out the code every time you want something done, you can simply call the function multiple times to get the same effect. This benefit is also known as "code reusability".


Example Function in JavaScript

A function that does not execute when a page loads should be placed inside the head of your HTML document. Creating a function is really quite easy. All you have to do is tell the browser you're making a function, give the function a name, and then write the JavaScript like normal. Below is the example alert function from the previous lesson.

Example:

<html>
<head>
<script type="text/javascript">
<!--
function popup() {
    alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="popup()" value="popup">
</body>
</html>
 

We first told the browser we were going to be using a function by typing "function". Next, we gave our function a name, so that we could use it later. Since we are making a pop up alert, we called our function "popup".

The curly braces "{,}" define the boundaries of our function code. All popup function code must be contained within the curly braces.

Something that might be slightly confusing is that within our "popup" function, we use another function called "alert," which brings up a popup box with the text that we supply it. It is perfectly OK to use functions within functions, like we have done here. Furthermore, this is one of the great things about using functions!

What we didn't talk about was how we got this function to execute when the button is clicked. The click is called an event, and we will be talking about how to make functions execute from various types of events in the next lesson.


Javascript Tutorial,Javascript Functions, Javascript Functions example, learn Javascript Functions,explain example Javascript Functions online free training Javascript Tutorial, Javascript Tutorial example, learn Javascript Functions, online tutorial, download tutorial, Javascript Tutorial books, Javascript Tutorial videos, live videos Javascript Tutorial, learn Javascript Tutorial, Javascript Tutorial topic Javascript Functions, live training Javascript Tutorial, download free tutorial