Microsoft Most Valuable Professional

Chris Pietschmann

An MVP From Wisconsin



JavaScript Function Tips and Tricks

First, What is a JavaScript Function? As defined by W3Schools.com a JavaScript Function is:

"A function is a reusable code-block that will be executed by an event, or when the function is called." - http://www.w3schools.com/js/js_functions.asp

You're probably thinking, "Well, Yeah. I knew that." But, how much do you really know about JavaScript Functions?

JavaScript Function uses you already know

Here's the most basic ways of using functions to get things done that most web developers are familiar with:

/// Function that performs an action 
function Test1()
{
    alert("Test1");
}

/// Function that accepts arguments and performs an action
function Test2(a, b)
{
    alert(a + b);
}

/// Function that returns returns a value
function Test3(a, b)
{
    return a + b;
}

Ok, but what else could there be?

Well, actually there are a couple more Function usages that most web developers aren't familiar with.

To test your knowledge of JavaScript Functions, take the following quiz:

1) Is it possible to write a JavaScript Function "in-line"?
2) Is it possible to overload a JavaScript Function?
3) Is it possible to call a JavaScript Function Asynchronously?

If you answered "Yes" to all three questions, then you're probably familiar with the tips listed in this article. If not, definitely read on.

In-Line JavaScript Functions

You can write JavaScript Function "in-line".

var myFunction = function(a, b){ return a + b; };

/// This actually does the exact same as the following:
function myFunction(a, b)
{
    return a + b;
}

You can also use "in-line" function to define custom functions for use within a specific context. This allows you to reference variables within the context that the "in-line" function was defined without having to actually pass them as arguments.

function AddNumbers(a, b)
{
    var add = function(){ return a + b; };

    return add();
}

JavaScript Function Overloading

If you're a .NET developer, then you're definitely used to overloading methods so you can pass in different combinations of arguments. Contrary to popular belief, JavaScript does support this. It's just in a different way.

The "arguments" variable within a Function is an Array that contains all the arguments that were passed in. You can use this to define your function "overloads".

function Test()
{
    /// Check how many arguments were passed in.
    alert("There were " + arguments.length + " argument(s) passed in.");
}

Here's an implementation of the above AddNumbers function that will add any number of values.

function AddNumbers()
{
    var r = 0;
    for(var i = 0; i < arguments.length; i++)
    {
        r += arguments[i];
    }
    return r;
}

You can also do some basic Type checking in JavaScript to overload your function for different object types.

function Test(a)
{
    /// Get the Type of the object passed in
    var t = typeof(a);

    /// Execute different code depending on the type passed in
    switch (t)
    {
        case "number":
            /// Number Type Overload Stuff Here
            break;
        case "string":
            /// StringType Overload Stuff Here
            break;
        case "boolean":
            /// Boolean Type Overload Stuff Here
            break;
        case "object":
            /// Object Type Overload Stuff Here
            break;
        default:
            alert("No overload exists for this object type: " + t);
    }

}

Calling JavaScript Function Asynchronously

One trick with JavaScript Functions is that you can essentially call them asynchronously by using Timeouts.

function AddNumbers(a, b)
{
    alert(a + b);
}

/// Call AddNumbers Asynchronously
window.setTimeout("AddNumbers(5, 10);", 1);

One thing to remember when executing functions asynchronously in JavaScript, is all other JavaScript execution in the page halts until a function call is completed. This is how all the current browsers execute JavaScript, and can cause real performance issues if you are trying to call too many things asynchronously at the same time. A long running function will actually "lock up" the browser for the user. The same is true for synchronous function calls too.

Another trick when calling function asynchronously is to pass in a callback function so your code can be notified when the function call is finished executing.

var asyncArguments = null;
var asyncCallback = null;

function AddNumbers(a, b, callback)
{
    // Save a reference to the arguments
    asyncArguments = arguments;

    // Save a reference to the callback function
    asyncCallback = callback;

    // Call Function Asynchronously
    window.setTimeout("AsynchronousAddNumbers();", 1);
}

function AsynchronousAddNumbers()
{
    // This is call asynchonously by AddNumbers, and then
    // calls the callback function when completed and passes
    // it the results.
    asyncCallback(asyncArguments[0] + asyncArguments[1]);
}

function AddNumbersCallback(result)
{
    // This gets called when AddNumbers is completed asynchronously
    alert(result);
}

/// TO USE:

/// Call AddNumbers to do our addition asynchronously
/// and pass it the callback function to call when done
AddNumbers(5, 10, AddNumbersCallback);

Conclusion

In this article we covered some tips and tricks of using JavaScript Functions. Using these tips, you'll be able to write functions that are more reusable and flexible.

If you have any additional tips, feel free to post them in the comments.

Currently rated 3.7 by 3 people

  • Currently 3.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: General
Posted by crpietschmann on Monday, February 25, 2008 5:45 PM
Permalink | Comments (3) | Post RSSRSS comment feed

Related posts

Comments

techtoolblog.com

Tuesday, February 26, 2008 10:18 PM

pingback

Pingback from techtoolblog.com

Daily Find #36 | TechToolBlog

paul irish us

Friday, February 29, 2008 3:03 AM

paul irish

It's considered poor form to send setTimeout a string--equivalent with using eval(). You're recommended to pass it a closure:

window.setTimeout(function(){ AsynchronousAddNumbers(); }, 1);

This also has the added benefit that whatever you're calling doesnt need to be global, and will work within your current scope.

ertbirth009.info

Wednesday, March 12, 2008 9:04 PM

pingback

Pingback from ertbirth009.info

belief net quiz

Comments are closed

About the author

I'm Chris Pietschmann, go to the About Me page to learn more about me.

Search

Sponsors

Web.Maps.VE - ASP.NET AJAX Virtual Earth Mapping Server Control

Recent comments

Disclaimer


This work is licensed under a Creative Commons Attribution 3.0 United States License, unless explicitly stated otherwise within the posted content.
© Copyright 2004 - 2008 Chris Pietschmann