Watch our 3-minute video to find out how you can learn JavaScript with a live instructor.
Additional Resources

JavaScript Functions

In this lesson of the JavaScript tutorial, you will learn...
  1. To work with some of JavaScript's built-in functions.
  2. To create your own functions.
  3. To return values from functions.

Built-in Functions

JavaScript has a number of built-in functions. We will examine some of them in this section.

Number(object)

The Number() function takes one argument: an object, which it attempts to convert to a number. If it cannot, it returns NaN, for "Not a Number."

Code Sample: JavaScriptFunctions/Demos/Number.html

<html>
<head>
 <title>Number() Function</title>
 <script type="text/javascript">
  var STR_NUM1 = "1";
  var STR_NUM2 = "2";
  var STR_SUM = STR_NUM1 + STR_NUM2; //returns 12
  alert(STR_SUM);
  
  var INT_NUM1 = Number(STR_NUM1);
  var INT_NUM2 = Number(STR_NUM2);
  var INT_SUM = INT_NUM1 + INT_NUM2; //returns 3
  alert(INT_SUM);
 </script>
</head>
<body>
 Nothing to show here.
</body>
</html>
Code Explanation

Because STR_NUM1 and STR_NUM2 are both strings, the + operator concatenates them, resulting in "12".

var STR_NUM1 = "1";
var STR_NUM2 = "2";
var STR_SUM = STR_NUM1 + STR_NUM2; //returns 12
alert(STR_SUM);

After the Number() function has been used to convert the strings to numbers, the + operator performs addition, resulting in 3.

var INT_NUM1 = Number(STR_NUM1);
var INT_NUM2 = Number(STR_NUM2);
var INT_SUM = INT_NUM1 + INT_NUM2; //returns 3
alert(INT_SUM);

String(object)

The String() function takes one argument: an object, which it converts to a string.

Code Sample: JavaScriptFunctions/Demos/String.html

<html>
<head>
 <title>String() Function</title>
 <script type="text/javascript">
  var INT_NUM1 = 1;
  var INT_NUM2 = 2;
  var INT_SUM = INT_NUM1 + INT_NUM2; //returns 3
  alert(INT_SUM);
  
  var STR_NUM1 = String(INT_NUM1);
  var STR_NUM2 = String(INT_NUM2);
  var STR_SUM = STR_NUM1 + STR_NUM2; //returns 12
  alert(STR_SUM);
 </script>
</head>
<body>
 Nothing to show here.
</body>
</html>
Code Explanation

Because INT_NUM1 and INT_NUM2 are both numbers, the + operator performs addition, resulting in 3.

var INT_NUM1 = 1;
var INT_NUM2 = 2;
var INT_SUM = INT_NUM1 + INT_NUM2; //returns 3
alert(INT_SUM);

After the String() function has been used to convert the numbers to string, the + operator performs concatenation, resulting in "12".

var STR_NUM1 = String(INT_NUM1);
var STR_NUM2 = String(INT_NUM2);
var STR_SUM = STR_NUM1 + STR_NUM2; //returns 12
alert(STR_SUM);

isNaN(object)

The isNaN() function takes one argument: an object. The function checks if the object is not a number (or cannot be converted to a number). It returns true if the object is not a number and false if it is a number.

Code Sample: JavaScriptFunctions/Demos/isNaN.html

<html>
<head>
 <title>isNaN() Function</title>
</head>
<body>
<table border="1" cellpadding="3" align="center">
<tr>
 <th>Function</th><th>Result</th>
</tr>
<script type="text/javascript">
 document.write("<tr><td>isNaN(4)</td>");
 document.write("<td>" + isNaN(4) + "</td></tr>");
 document.write("<tr><td>isNaN(\"4\")</td>");
 document.write("<td>" + isNaN("4") + "</td></tr>");
 document.write("<tr><td>isNaN(0/0)</td>");
 document.write("<td>" + isNaN(0/0) + "</td></tr>");
 document.write("<tr><td>isNaN(\"hello\")</td>");
 document.write("<td>" + isNaN("hello") + "</td></tr>");
 var AGE_STR = "twelve";
 document.write("<tr><td>isNaN(AGE_STR)</td>");
 document.write("<td>" + isNaN(AGE_STR) + "</td></tr>");
 var AGE_INT = 12;
 document.write("<tr><td>isNaN(AGE_INT)</td>");
 document.write("<td>" + isNaN(AGE_INT) + "</td></tr>");
</script>
</table>
</body>
</html>
Code Explanation

The output will look like this:

parseFloat() and parseInt()

The parseFloat() function takes one argument: a string. If the string begins with a number, the function reads through the string until it finds the end of the number, hacks off the remainder of the string, and returns the result. If the string does not begin with a number, the function returns NaN.

The parseInt() function also takes one argument: a string. If the string begins with an integer, the function reads through the string until it finds the end of the integer, hacks off the remainder of the string, and returns the result. If the string does not begin with an integer, the function returns NaN.

Code Sample: JavaScriptFunctions/Demos/ParsingNumbers.html

<html>
<head>
 <title>Parsing for Numbers</title>
</head>
<body>
<table border="1" cellpadding="3" align="center">
<tr>
 <th>Function</th><th>Result</th>
</tr>
<script type="text/javascript">
 var RACE = "26.2 miles";
 document.write("<tr><td>parseFloat(RACE)</td>");
 document.write("<td>" + parseFloat(RACE) + "</td></tr>");
 document.write("<tr><td>parseInt(RACE)</td>");
 document.write("<td>" + parseInt(RACE) + "</td></tr>");
 RACE = "Marathon";
 document.write("<tr><td>parseFloat(RACE)</td>");
 document.write("<td>" + parseFloat(RACE) + "</td></tr>");
 document.write("<tr><td>parseInt(RACE)</td>");
 document.write("<td>" + parseInt(RACE) + "</td></tr>");
</script>
</table>
</body>
</html>
Code Explanation

The output will look like this:

Built-in Functions vs. Methods

Methods and functions are similar in that they both make things happen. They are also syntactically similar. The major difference is that methods are tied to an object; whereas, functions are not. For example, alert() is a method of the window object; whereas parseInt() is a standalone function.

Exercise: Working with Built-in Functions

Duration: 15 to 25 minutes.

In this exercise, you will practice working with JavaScript's built-in functions.

  1. Open JavaScriptFunctions/Exercises/BuiltinFunctions.html for editing.
  2. Modify the file so that it outputs the sum of the two numbers entered by the user.

Code Sample: JavaScriptFunctions/Exercises/BuiltinFunctions.html

<html>
<head>
 <title>JavaScript Operators</title>
 <script type="text/javascript">
  var USER_NUM1, USER_NUM2, NUMS_ADDED;
  USER_NUM1 = window.prompt("Choose a number.", "");
  alert("You chose " + USER_NUM1);
  USER_NUM2 = window.prompt("Choose another number.", "");
  alert("You chose " + USER_NUM2);
  NUMS_ADDED = USER_NUM1 + USER_NUM2;
 </script>
</head>
<body>
<p style="text-align:center; font-size:large">
 <script type="text/javascript">
  document.write(USER_NUM1 + " + " + USER_NUM2 + " = ");
  document.write(NUMS_ADDED + "<br/>");
 </script>
</p>
</body>
</html>

Create a new HTML file that prompts the user for his name, the age at which he first worked on a computer, and his current age. After gathering this information, pop up an alert that tells the user how many years he's been working on a computer. The images below show the steps:

Notice that the program is able to deal with numbers followed by strings (e.g, "12 years old").

User-defined Functions

Writing functions makes it possible to reuse code for common tasks. Functions can also be used to hide complex code. For example, an experienced developer can write a function for performing a complicated task. Other developers do not need to know how that function works; they only need to know how to call it.

Function Syntax

JavaScript functions generally appear in the head of the page or in external JavaScript files. A function is written using the function keyword followed by the name of the function.

Syntax
function doSomething(){
 //function statements go here
}

As you can see, the body of the function is contained with in curly brackets ({}). The following example demonstrates the use of simple functions.

Code Sample: JavaScriptFunctions/Demos/SimpleFunctions.html

<html>
<head>
 <title>JavaScript Simple Functions</title>
 <script type="text/javascript">
  function changeBgRed(){
   document.bgColor = "red";
  }
  
  function changeBgWhite(){
   document.bgColor = "white";
  }
 </script>
</head>
<body>
<p align="center">
 <span onclick="changeBgRed();">Red</span> |
 <span onclick="changeBgWhite();">White</span>
</p>
</body>
</html>

Passing Values to Functions

The functions above aren't very useful because they always do the same thing. Every time we wanted to add another color, we would have to write another function. Also, if we want to modify the behavior, we will have to do it in each function. The example below shows how to create a single function to handle changing the background color.

Code Sample: JavaScriptFunctions/Demos/PassingValues.html

<html>
<head>
 <title>JavaScript Simple Functions</title>
 <script type="text/javascript">
  function changeBg(color){
   document.bgColor = color;
  }
 </script>
</head>
<body>
<p align="center">
 <span onclick="changeBg('red');">Red</span> |
 <span onclick="changeBg('white');">White</span>
</p>
</body>
</html>
Code Explanation

As you can see, when calling the changeBG() function, we pass a value (e.g, 'red'), which is assigned to the color variable. We can then refer to the color variable throughout the function. Variables created in this way are called function arguments or parameters. A function can have any number of arguments, separated by commas.

A Note on Variable Scope

Variables created through function arguments or declared within a function with var are local to the function, meaning that they cannot be accessed outside of the function.

Variables declared with var outside of a function and variables that are used without being declared are global, meaning that they can be used anywhere on the page.

Exercise: Writing a JavaScript Function

Duration: 15 to 25 minutes.

In this exercise, you will modify a page called ColorMania.html, which will contain a form with four buttons. Each button will show the name of a color (e.g, red) and, when clicked, call a function that changes the background color. The buttons you will create will be of type button. For example,

<input type="button" value="red" onclick="functionCall();">

  1. Open JavaScriptFunctions/Exercises/ColorMania.html for editing.
  2. Write code to prompt the user for her name.
  3. Write a function called changeBg() that changes the background color and then pops up an alert telling the user, by name, what the new background color is.
  4. In the form, add four buttons that, when clicked, call the changeBg() function and pass it a color value.

The resulting page should look like this:

Code Sample: JavaScriptFunctions/Exercises/ColorMania.html

<html>
<head>
 <title>Colormania</title>
 <script type="text/javascript">
  //PROMPT USER FOR NAME
  
  /*
  Write a function called changeBg() that changes the background
  color and then pops up an alert telling the user, by name, what
  the new background color is.
  */
 </script>
</head>
<body>
<form style="text-align:center">
 <!--ADD BUTTONS HERE-->
</form>
</body>
</html>

Add another button called "custom" that, when clicked, prompts the user for a color, then changes the background color to the user-entered color and alerts the user to the change.

Returning Values from Functions

The return keyword is used to return values from functions as the following example illustrates.

Code Sample: JavaScriptFunctions/Demos/ReturnValue.html

<html>
<head>
<title>Returning a Value</title>
<script type="text/javascript">
function setBgColor(){
 document.bgColor = prompt("Set Background Color:", ""); 
}

function getBgColor(){
 return document.bgColor;
}
</script>
</head>

<body>
<form>
 <input type="button" value="Set Background Color"
  onclick="setBgColor();">
 <input type="button" value="Get Background Color"
  onclick="alert(getBgColor());">
</form>
</body>
</html>
Code Explanation

When the user clicks on the "Get Background Color" button, an alert pops up with a value returned from the getBgColor() function. This is a very simple example. Generally, functions that return values are a bit more involved. We'll see many more functions that return values throughout the course.

JavaScript Functions Conclusion

In this lesson of the JavaScript tutorial, you have learned to work with JavaScript's built-in functions and to create functions of your own.

To continue to learn JavaScript go to the top of this page and click on the next lesson in this JavaScript Tutorial's Table of Contents.

Use of http://www.learn-javascript-tutorial.com (Website) implies agreement to the following:

Copyright Information

All pages and graphics on Website are the property of Webucator, Inc. unless otherwise specified.

None of the content on Website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of pages or content on Website

This content may not be printed or saved. It is for online use only.


Linking to Website

You may link to any of the pages on Website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

Website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).


For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm