facebook twitter
Webucator's Free JavaScript Tutorial

Lesson: JavaScript Functions

Welcome to our free JavaScript tutorial. This tutorial is based on Webucator's Introduction to JavaScript Training course.

In this lesson, you will learn how to work with JavaScript functions.

Lesson Goals

  • Learn to work with some of JavaScript's global functions.
  • Learn to create your own functions.
  • Learn to return values from functions.

Global Objects and Functions

A "global" function or object is one that is accessible from anywhere. JavaScript has a number of global objects and functions. We will examine some of them in this section.

parseFloat(object)

The parseFloat() function takes one argument: an object, and attempts to return a floating point number, which is a decimal number. If it cannot, it returns NaN, for "Not a Number."

Remember when we "add" two strings using the plus sign (+), the strings are concatenated together, as the following code illustrates: Adding Strings

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

We can use parseFloat() to convert those strings to numbers before adding them:Converting strings to numbers with parseFloat.

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

If the value passed to parseFloat() doesn't start with a number, the function returns NaN.parseFloat - NaN

parseInt(object)

The parseInt() function is similar to parseFloat(). It takes one argument: an object, and attempts to return an integer. If it cannot, it returns NaN, for "Not a Number."

As you can see from the code below, parseInt() just strips everything to the right of the first integer it finds. If the value passed to parseInt() doesn't start with an integer, the function returns NaN.parseInt

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.parseInt

As you can see from the code above, if the passed-in value is a number or can be converted into a number (e.g., 4 and '4'), isNaN() returns false. Otherwise (e.g., 'hello'), it returns true, meaning that it is indeed Not a Number.

Working with Global Functions

Duration: 10 to 15 minutes.

In this exercise, you will practice working with JavaScript's global functions.

  1. Open JavaScriptFunctions/Exercises/built-in-functions.html for editing.
  2. As the code is currently written (see below), it will concatenate the user-entered numbers rather than add them. Fix this so that it outputs the sum of the two numbers entered by the user.

Code Sample:

JavaScriptFunctions/Exercises/built-in-functions.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  var userNum1, userNum2, numsAdded;
  userNum1 = window.prompt("Choose a number.", "");
  alert("You chose " + userNum1);
  userNum2 = window.prompt("Choose another number.", "");
  alert("You chose " + userNum2);
  numsAdded = userNum1 + userNum2;
</script>
<title>JavaScript Built-in Functions</title>
</head>
<body>
<p>
  <script>
    document.write(userNum1 + " + " + userNum2 + " = ");
    document.write(numsAdded);
  </script>
</p>
</body>
</html>

Code Explanation

Challenge

Create a new HTML file that prompts the user for

  1. Their name:Built-in functions challenge 1. The age at which they first worked on a computer:Built-in functions challenge 2. And their current age:Built-in functions challenge 3.After gathering this information, write out to the page how many years they have been working on a computer: Built-in functions challenge 4.

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

Solution:

JavaScriptFunctions/Solutions/built-in-functions.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  var userNum1, userNum2, numsAdded;
  userNum1 = window.prompt("Choose a number.", "");
  alert("You chose " + userNum1);
  userNum2 = window.prompt("Choose another number.", "");
  alert("You chose " + userNum2);
  numsAdded = parseFloat(userNum1) + parseFloat(userNum2);
</script>
<title>JavaScript Built-in Functions</title>
</head>
<body>
<main>
  <p>
  <script>
    document.write(userNum1 + " + " + userNum2 + " = ");
    document.write(numsAdded);
  </script>
  </p>
</main>
</body>
</html>

Code Explanation

Challenge Solution:

JavaScriptFunctions/Solutions/built-in-functions-challenge.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  var userName = prompt("What's your name?");
  var age1 = prompt('How old were you when you first used a computer?');
  var age2 = prompt('How old are you now?');
  var diff = parseFloat(age2) - parseFloat(age1);
</script>
<title>JavaScript Built-in Functions</title>
</head>
<body>
<main>
  <p>
  <script>
    document.write(userName + ', you have used '
                  +'computers for ' + diff + ' years.');
  </script>
  </p>
</main>
</body>
</html>

Code Explanation

You may have noticed that we are not including the second argument, which is the default value, for prompt() in the challenge solution. While these could be written as var age2 = prompt("How old are you now?","");, this is not necessary as an empty string is the default value.

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 within curly brackets ({}). The following example demonstrates the use of simple functions:

Code Sample:

JavaScriptFunctions/Demos/simple-functions.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  function changeBgRed() {
    document.body.style.backgroundColor = "red";
  }
  
  function changeBgWhite() {
    document.body.style.backgroundColor = "white";
  }
</script>
<title>JavaScript Simple Functions</title>
</head>
<body>
  <button onclick="changeBgRed();">Red</button>
  <button onclick="changeBgWhite();">White</button>
</body>
</html>

Code Explanation

When the user clicks on one of the buttons, the event is captured by the onclick event handler and the corresponding function is called.

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/passing-values.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  function changeBg(color) {
    document.body.style.backgroundColor = color;
  }
</script>
<title>Passing Values</title>
</head>
<body>
  <button onclick="changeBg('red');">Red</button>
  <button onclick="changeBg('white');">White</button>
</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 "parameters" and the values passed to them are called "arguments". A function can have any number of parameters, separated by commas.

Adding parameters to functions makes them more flexible and, thus, more useful; as you saw above, we can call the changeBg() function many times, passing to it a different color as needed. We can make our functions even more useful by providing default values for parameters so that, if the function is called without an argument, we assign some default value to the parameter. Here's how we might modify our earlier example:

Code Sample:

JavaScriptFunctions/Demos/passing-values-default-param.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  function changeBg(color='blue') {
    document.body.style.backgroundColor = color;
  }
</script>
<title>Passing Values - Default Param</title>
</head>
<body>
<p>
  <button onclick="changeBg('red');">Red</button>
  <button onclick="changeBg('white');">White</button>
  <button onclick="changeBg();">Blue (no param)</button>
</p>
</body>
</html>

Code Explanation

We've added a default value for function changeBg's color parameter, giving it the value blue if no value is supplied when the function is called. We've also added a third button on which the user can click; here we call changeBg() (without a parameter for color) and thus get the default color "blue".

A Note on Variable Scope

A variable's "scope" is the context in which the variable can be referenced. Variables created by passing arguments to function parameters are local to the function, meaning that they cannot be accessed outside of the function. The same is true for variables declared within a function using the var keyword.

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

Returning Values from Functions

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

Code Sample:

JavaScriptFunctions/Demos/return-value.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
function setBgColor() {
  var bg = prompt("Set Background Color:", "");
  document.body.style.backgroundColor = bg; 
}

function getBgColor() {
  return document.body.style.backgroundColor;
}
</script>
<title>Returning a Value</title>
</head>
<body>
  <button onclick="setBgColor()">Set Background Color</button>
  <button onclick="alert(getBgColor())">Get Background Color</button>
</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.

Writing a JavaScript Function

Duration: 15 to 25 minutes.

In this exercise, you will modify a page called resize-box.html, which will contain a box and two buttons for resizing the box: ResizeBox Solution

  1. Open JavaScriptFunctions/Exercises/resize-box.html for editing.
  2. Notice that the page has a div with the id "box" and width and height styles set.
  3. The page also contains two buttons that call resizeBox() passing in -10 and 10 for the change argument.
  4. Write a function called resizeBox() that has one parameter: change, which is the amount the width and height of the box should be changed. The default value of change should be 10. The resizeBox() function will need to do the following:
    1. Declare a variable box that holds the "box" div. You will do this using document.getElementById(), which is a method for accessing elements on the page by their id value:
      var box = document.getElementById('box');
    2. Declare a variable w that holds the current width of the box. You will do this with the following line of code:
      var w = box.style.width;
      Note that the value will be a string ending in "px" as shown below. This is because width and height style values take a number and a unit.ResizeBox Solution get box
    3. Just as you did for width, declare a variable h that holds the current height of the box.
    4. Declare variables wNew and hNew that contain the new width and height values. Note that you will need to add the value of change to the current values of w and h, but before doing so, you will need to strip off the "px" from w and h and convert those values to numbers. You can do that with parseInt().
    5. Assign the new values of w and h to box.style.width and box.style.height. Note that you will need to append (concatenate) "px" back to those values.

Code Sample:

JavaScriptFunctions/Exercises/resize-box.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
  // Write your code here
</script>
<title>Resize Box</title>
</head>
<body id="resize-box">
<main>
  <div id="box" style="width:100px; height:100px; 
          background-color:blue;"></div>
  <button onclick="resizeBox(-10)">SHRINK</button>
  <button onclick="resizeBox(10)">GROW</button>
</main>
</body>
</html>

Code Explanation

Challenge

Add separate buttons for changing height and width.ResizeBox Challenge Solution As we haven't learned to write conditional code yet, you will need to write separate functions; for example, resizeBoxHeight() and resizeBoxWidth().

Solution:

JavaScriptFunctions/Solutions/resize-box.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
function resizeBox(change=10) {
  var box = document.getElementById('box');
  var w = box.style.width;
  var h = box.style.height;
  var wNew = parseInt(w) + change;
  var hNew = parseInt(h) + change;
  box.style.width = wNew + 'px';
  box.style.height = hNew + 'px';
}
</script>
<title>Resize Box</title>
</head>
<body id="resize-box">
<main>
  <div id="box" style="width:100px; height:100px;"></div>
  <button onclick="resizeBox(-10)">SHRINK</button>
  <button onclick="resizeBox(10)">GROW</button>
</main>
</body>
</html>

Code Explanation

Challenge Solution:

JavaScriptFunctions/Solutions/resize-box-challenge.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="../normalize.css">
<link rel="stylesheet" href="../styles.css">
<script>
function resizeHeight(change=10) {
  var box = document.getElementById('box');
  var h = box.style.height;
  var hNew = parseInt(h) + change;
  box.style.height = hNew + 'px';
}

function resizeWidth(change=10) {
  var box = document.getElementById('box');
  var w = box.style.width;
  var wNew = parseInt(w) + change;
  box.style.width = wNew + 'px';
}
</script>
<title>Resize Box - Challenge</title>
</head>
<body id="resize-box">
<main>
  <div id="box" style="width:100px; height:100px;"></div>
  <button onclick="resizeHeight(-10)">SHRINK HEIGHT</button>
  <button onclick="resizeHeight(10)">GROW HEIGHT</button><br>
  <button onclick="resizeWidth(-10)">SHRINK WIDTH</button>
  <button onclick="resizeWidth(10)">GROW WIDTH</button>
</main>
</body>
</html>