Javascript Tutorial -- Using Functions in Javascript



I was first introduced to "structured programming" when I was in high school. Structured programming is a way of writing code in a form that is neat, easy to read and easy to modify. Because the code is neat, easy to read and easy to modify, it is usually more reliable and often times more efficient than code that was not written with a structured approach.

One of the core concepts in structured programming is that you break your code into smaller modules, each of which performs a single function. Appropriately enough, in Javascript, these modules are called "functions". Here is a simple function in Javascript:
        <script type="text/javascript">
          <!--
            function hello()
              {
                window.alert("Hello, world!")
              }
          //-->
        </script>
      
If you copy and paste this snippet of code into an HTML document, you will probably be disappointed to see that nothing happens. This is because a function doesn't do anything until another part of your code "calls" (runs) the function. To some degree, you can think of functions as being like mini-programs inside your main program. If you have ever written a program in C, Perl, Python, Basic, Pascal or any other programming language, did it run as soon as you saved it to your computer's hard drive? Of course not -- you had to run the program before it did anything. In much the same way, your HTML document must send a request to have the Javascript function run before it executes. There are a number of ways to have your HTML document call a Javascript function; here are two examples:
        <script type="text/javascript">
          <!--
            function hello()
              {
                window.alert("Hello, world!")
              }

            hello()
          //-->
        </script>
      
        <script type="text/javascript">
          <!--
            function hello()
              {
                window.alert("Hello, world!")
              }
          //-->
        </script>
        <input type="button" onClick="hello()" value="Click">
      
In the first example, the script will run the "hello" function as soon as the web page loads. In the second example, the "hello" function is not called until the user clicks the button on the web page.

Did you notice the parenthesis after the function name in the function definition and when the function was called? A function that could not accept data from the main program would only have limited usefulness, since one of the main reasons to use functions is to reuse the same code in different parts of the program. If you have data you want to be available to the function, you include it in between the parenthesis. Functions can accept either literal data or a variable. For example, both of these snippets of code will produce the same output:
        <script>
          <!--
            function hello(Name)
              {
                window.alert(Name)
              }

            hello("Mike")
          //-->
        </script>
      
        <script>
          <!--
            var Name

            function hello(Name)
              {
                window.alert(Name)
              }

            Name = "Mike"
            hello(Name)
          //-->
        </script>
      
So how does Javascript know if you are sending a literal value to act upon or if you are sending the name of a variable? If you are observant, you will notice that in the first example, the name "Mike" is surrounded by quotation marks, but in the second example, the variable "Name" is not. Anything in quotes is literal; anything not in quotes is assumed to be a variable.

Here's a trick question for you. In one of the examples above, the "hello" function is called when the user clicks on an input button. Here's the code again:
        <script type="text/javascript">
          <!--
            function hello()
              {
                window.alert("Hello, world!")
              }
          //-->
        </script>
        <input type="button" onClick="hello()" value="Click">
      
Did you notice the code that calls the function inside the "onClick" attribute is in quotes? How would you send literal data in this case? Javascript will accept literal data in either single or double quotes, so you could rewrite the input tag as follows (assuming the "hello" function were also rewritten to accept data):
        <input type="button" onClick="hello('Mike')" value="Click">
      
Still with me? Good -- there's only one last tidbit of information about functions to cover before you'll have the basics down. It's all well and good to be able to send data to a function and produce some output, but suppose you want to write a function to compute something, but you don't necessarily want to write it to the web browser? Not to worry -- not only can Javascript accept data from the main program, but it can return data as well. Here's how you do it:
        <script>
          <!--
            function AreaOfACircle(radius)
              {
                var Area = 3.1415 * radius * radius

                return(Area)
              }

            document.write(AreaOfACircle("5"))
          //-->
        </script>
      


The "return" keyword tells the function to terminate and return the data inside the parenthesis to the main program.

Here's an example of an HTML document that uses functions.