Home arrow JavaScript arrow Page 2 - Variables, Functions, and Flow Control

Variables, Functions, and Flow Control

This two-part series offers a mix of JavaScript tricks to help you with your everyday projects. It is excerpted from chapter 4 of the JavaScript & DHTML Cookbook, Second Edition, written by Danny Goodman (O'Reilly, 2008; ISBN: 0596514085). Copyright 2008 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 5 stars5 stars5 stars5 stars5 stars / 15
December 11, 2009
  1. · Variables, Functions, and Flow Control
  2. · 4.2 Creating a Named Function
  3. · 4.3 Nesting Named Functions
  4. · 4.4 Creating an Anonymous Function

print this article

Variables, Functions, and Flow Control - 4.2 Creating a Named Function
(Page 2 of 4 )


You want to define a function that can be invoked from any statement in the page.


For a function that receives no parameters, use the simple function declaration format:

  function myFunctionName() {
// statements go here

If the function is designed to receive parameters from the statement that invokes the function, define parameter variable names in the parentheses following the function name:

  function myFunctionName(paramVar1, paramVar2[, ..., paramVarN]) {
// statements go here

You can define as many unique parameter variable identifiers as you need. These variables become local variables inside the function (var declarations are implied). Following JavaScript's loosely typed conventions, parameter variables may hold any valid data type, as determined by the statement that invokes the function and passes the parameters.

Curly braces that contain the statements belonging to the function are required only when two or more statements are inside the function. It is good practice to use curly braces anyway, even for one-line statements, to assist in source code readability (a convention followed throughout this book).

The majority of long scripts throughout this book employ named functions, some with parameters, others without. Real-world examples abound, especially in
recipes containing external JavaScript libraries, such as the DHTML API library in Recipe 13.3.


A function is an object type in JavaScript, and the name you assign to the function becomes a case-sensitive identifier for that object. As a result, you cannot use a JavaScript-reserved keyword as a function name, nor should you use a function name that is also an identifier for one of your other global entities, such as variables or (in IE and Safari) element IDs. If you have two functions with the same name in a page, the one that comes last in source code order is the only available version. JavaScript does not implement the notion of function or method overloading found in languages such as Java (where an identically named method with a different number of parameter variables is treated as a separate method).

Invoke a function using parentheses:


At times, you will need to assign a function's reference to a property. For example, when you assign event handlers to element object properties (see Chapter 9), the assignment consists of a function reference. Such a reference is the name of the function but without parentheses, parameters, or quotes:

  document.onclick = myFunc;

This kind of property assignment is merely setting the stage for a future invocation of the function, where parameters may be passed, if necessary.

Some programming languages distinguish between executable blocks of code that operate on their own and those that return values. In JavaScript, there is only one kind of function. If the function includes a return statement, the function returns a value; otherwise, there is no returned value. Functions used as what other environments might call subroutines commonly return values simply because you define them to perform some kind of information retrieval or calculation, and then return the result to the statement that invoked the routine. When a function returns a value, the call to the function evaluates to a value that can be assigned immediately to a variable or be used as a parameter value to some other function or method. Recipe 15.7 demonstrates this feature. Its job is to display the part of the day (morning, afternoon, or evening) in a welcome greeting that is written to the page as it loads. A function called getDayPart() (defined in the head portion of the page) calculates the current time and returns a string with the appropriate day part:

  function dayPart() {
var oneDate = new Date();
var theHour = oneDate.getHours();
if (theHour < 12) {
return "morning";
      } else if (theHour < 18) {
          return "afternoon";
      } else {
          return "evening";

That function is invoked as a parameter to the document.write() method that places the text in the rendered page:

  <script type="text/javascript">
  document.write("Good " + dayPart() + " and welcome")
   to GiantCo.

It is not essential to pass the same number of arguments to a function, as you have defined parameter variables for that function. For example, if the function is called from two different places in your script, and each place provides a different number of parameters, you can access the parameter values in the function by way of the arguments property of the function rather than by parameter variables:

  function myFunc() {
for (var i = 0; i < myFunc.arguments.length; i++) {
// each entry in the arguments array is one parameter value
// in the order in which they were passed

A typical function (except a nested function, as described in Recipe 4.3) exists in the global context of the window housing the current page. Just as with global variables, these global functions can be referenced by script statements in other windows and frames. See "Frames As Window Objects" in Chapter 7 for examples of referencing content in other frames.

How large a function should be is a matter of style. For ease of debugging and maintenance, it may be appropriate to divide a long function into sections that either branch out to subroutines that return values or operate in sequence from one function to the next. When you see that you use a series of statements two or more times within a large function, these statements are excellent candidates for removal to their own function that gets called repeatedly from the large function.

The other stylistic decision in your hands is where you place the curly braces. This book adopts the convention of starting a curly brace pair on the same line as the function name, and closing the pair at the same tab location as the function declaration. But you can place the opening curly brace on the line below the function name, and left-align it if you like:

  function myFunc()
// statements go here

Some coders feel this format makes it easier to keep brace pairs in sync. For a one-line function, the single statement can go on the same line as the function name:

  function myFunc() {//statement goes here}

Adopt the style that makes the most logical sense to you and your code-reading eye.

See Also

Recipe 4.1 for a discussion about variables "by reference and by value"--a discussion that applies equally to function parameter variables; Recipe 4.3 for nesting functions.

blog comments powered by Disqus

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials