Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Create Custom Functions with a Return Value in JavaScript

Many of the built-in functions in JavaScript provide some sort of return value to program with HTML, and you can create functions that provide a return value, too. Use a return value when the function performs a simple task that could be part of a more complex task.

For example, when working with a string, you can use the toUpperCase() function to change the case of a string that might be manipulated in other ways. Changing the case of a string is a simple, well-defined task, but it could be part of a larger task, and so it provides a return value for that reason. Here’s an example of a function with a return value:

function TestReturn()
{
  return document.title;
}

In this case, the function returns the document’s title. The caller may want to do more with the text, so it’s returned rather than output directly in some way. In this case, the caller adds some additional text to the output and displays it onscreen, as shown here:

function DisplayReturn()
{
  // Output the param onscreen.
  document.getElementById("Result").innerHTML =
   "The return value is: " + TestReturn();
}

Using return values lets you nest function calls as deeply as needed to perform complex tasks. When you create an application, break complex tasks down into smaller tasks. If you find that the smaller tasks are still too complicated, break these subtasks down into smaller tasks. It’s important to create functions that perform a single task but also perform that single task well.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!