Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

'Personalized JavaScript': User-defined functions, objects, and methods

How to take full advantage of JavaScript by moving beyond its built-in commands

  • Print
  • Feedback
As a modern programming language, JavaScript endorses full extensibility by letting you define your own functions. This allows you to create routines you can use over and over again. You save time in re-using common "components," and by designing your own functions you can extend JavaScript's base language to suit your needs. Think of it as "personalized JavaScript."

Since JavaScript is based on objects, a JavaScript function can easily be turned into an object, and a method for that object. So, not only can you create user-defined objects to do your bidding, you can create your own objects that behave in exactly the way you want. And you can create methods that act upon those objects. While this sounds powerful -- and it is -- the process of creating functions, objects, and methods is very easy in JavaScript.

Introducing functions

Use the function statement to create your own JavaScript function. The bare-bones syntax is:

function name (params) {
    ... function stuff...
}


  • name is the unique name of the function. All function names in a script must be unique.
  • params is one or more parameter variables you pass to the function.
  • function stuff is the instructions carried out by the function. You can put most anything here.


Notice the { and } brace characters; these define the function block, and are absolutely necessary. The braces tell JavaScript where a function begins and ends. The parentheses around the parameters also are required. Include the parentheses even if the function doesn't use parameters (and many don't).

Names for your user-defined functions are up to you, just as long as you use only alphanumeric characters (the underscore character _ also is permitted). Function names must start with a letter character, but can include numbers elsewhere in the name.

I've stuck with the JavaScript style of function name capitalization -- that is, initial lower case, then upper-case characters if the function name is composed of composite words. For example, myFuncName, yourFuncName, or theirFuncName. Function names are case-sensitive; be sure to use the same capitalization when you refer to the function elsewhere in the script. JavaScript considers myFunc different from Myfunc.

  • Print
  • Feedback

Resources