Home > Articles > Open Source > Ajax & JavaScript

Using Functions in JavaScript

  • Print
  • + Share This
  • 💬 Discuss
Functions are one of the basic building blocks of JavaScript and will appear in virtually every script you write. In this excerpt learn how to create and use functions.

Commonly, programs carry out the same or similar tasks repeatedly during the course of their execution. For you to avoid rewriting the same piece of code over and over again, JavaScript has the means to parcel up parts of your code into reusable modules, called functions. After you’ve written a function, it is available for the rest of your program to use, as if it were itself a part of the JavaScript language.

Using functions also makes your code easier to debug and maintain. Suppose you’ve written an application to calculate shipping costs; when the tax rates or haulage prices change, you’ll need to make changes to your script. There may be 50 places in your code where such calculations are carried out. When you attempt to change every calculation, you’re likely to miss some instances or introduce errors. However, if all such calculations are wrapped up in a few functions used throughout the application, then you just need to make changes to those functions. Your changes will automatically be applied all through the application.

Functions are one of the basic building blocks of JavaScript and will appear in virtually every script you write. In this hour you see how to create and use functions.

General Syntax

Creating a function is similar to creating a new JavaScript command that you can use in your script.

Here’s the basic syntax for creating a function:

function sayHello() {
    alert("Hello");
    // ... more statements can go here ...
}

You begin with the keyword function, followed by your chosen function name with parentheses appended, then a pair of curly braces {}. Inside the braces go the JavaScript statements that make up the function. In the case of the preceding example, we simply have one line of code to pop up an alert dialog, but you can add as many lines of code as are necessary to make the function...well, function!

To keep things tidy, you can collect together as many functions as you like into one <script> element:

<script>
    function doThis() {
        alert("Doing This");
    }
    function doThat() {
        alert("Doing That");
    }
</script>
  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus