Home arrow JavaScript arrow Page 4 - 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.4 Creating an Anonymous Function
(Page 4 of 4 )


You want to define a function in the form of an expression that you can, for example, pass as a parameter to an object constructor or assign to an object's method.


You can use an alternative syntax for defining functions without creating an explicitly named function (as shown in Recipe 4.2). Called an anonymous function, this syntax has all the components of a function definition except its identifier. The syntax model is as follows:

  var someReference = function() {statements go here};

Statements inside the curly braces are semicolon-delimited JavaScript statements. You can define parameter variables if they're needed:

  var someReference = function(paramVar1[,..., paramVarN]) {statements go here};

Invoke the function via the reference to the function:



Anonymous function creation returns an object of type function. Therefore, you can assign the right side of the statement to any assignment statement where a function reference (the function name without parentheses) is expected. To demonstrate, we'll make a version of a shortcut object constructor from Recipe 3.8. It starts with an ordinary function definition that gets invoked as a method of four objects defined with shortcut syntax:

  function showAll() {
alert("Employee " + this.name + " is " + this.age + " years old.");
  var employeeDB = [{name:"Alice", age:23, show:showAll},
{name:"Fred", age:32, show:showAll},
{name:"Jean", age:28, show:showAll},
{name:"Steve", age:24, show:showAll}];

Notice how in the object constructors, a reference to the showAll() function is assigned to the show method name. Invoking this method from one of the objects is done in the following manner:


For the sake of example, we assign an anonymous function to the first object. The anonymous function is custom-tailored for the first object and replaces the reference to showAll():

  var employeeDB = [{name:"Alice", age:23,
                        {alert("Alice\'s age is not open to the public.")}},
{name:"Fred", age:32, show:showAll},
                    {name:"Jean", age:28, show:showAll},
                    {name:"Steve", age:24, show:showAll}];

Now, if you invoke employeeDB[0].show(), the special alert displays itself because the anonymous function is running instead of the showAll() function. We have saved the need to create an external function with its own identifier just to act as an intermediary between the show method name and the statements to execute when the method is invoked.

Assigning anonymous function definitions to object properties--thus creating object methods--is a good way to remove groups of related functions from the global scope. In large projects containing multiple libraries or frameworks (often from multiple authoring sources), unintentionally redundant function names can cause havoc. See Recipe 3.14 for suggestions on minimizing such conflicts.

See Also

Recipe 4.3 for creating traditional named functions; Recipe 3.14 for using anonymous functions to reduce global naming conflicts.

Please check back Monday for the conclusion to this article.

DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

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