JavaScript For Kids For Dummies
Book image
Explore Book Buy On Amazon

Functions are programs inside of programs. Functions in JavaScript are great at handling tasks that may be required multiple times by different parts of a program. They're also a great way to keep things organized within your program.

Built‐in functions

Some functions are built into JavaScript, such as the methods of arrays, strings, numbers, and other objects. You can tell that something's a function because it has parentheses after it.

When a function is part of an object (such as the document object, for example) it's called a method. But it's still a function.

Here are some of the functions that are built into JavaScript:


Can you think of other functions you've seen?

Custom functions

In addition to the functions that are built into JavaScript, you can also create your own!

You can't spell function without "fun," and you can't write JavaScript code without using functions. Therefore, you can't write JavaScript code without having fun!

Here's an example of a function that adds a smiley face to any text you give it:

function smileyIt(theText) {
  theText += " :)";
  return theText;

Follow these steps to try out this function:

  1. Open in your web browser.

    You should have a blank project. If it's not blank, click the JSFiddle logo in the upper‐left corner of the screen.

  2. Type the code for the smileyIt() function into the JavaScript pane.

  3. Click the Run button.

    Notice that nothing happens. Unlike JavaScript code that's outside a function, code inside functions doesn't run until the function is called.

  4. Add the following statement underneath the function:

    smileyIt("Hi There!");
  5. Click the Run link.

    Once again, nothing appears to have happened. But this time, something actually did happen. The results of running the function just weren't reported back to you.

  6. Modify the statement you wrote in the last step to put the result of running the function into an alert popup, like this:

    alert(smileyIt("Hi there!"));
  7. Click the Run link.

    If you entered everything correctly, you should get an alert popup saying Hi there! :), as shown here.

    Outputting the result of the function to an alert.
    Outputting the result of the function to an alert.

alert() is another example of a built‐in JavaScript function!

About This Article

This article is from the book:

About the book authors:

Chris Minnick and Eva Holland are experienced web developers, tech trainers, and coauthors of Coding with JavaScript For Dummies. Together they founded WatzThis?, a company focused on training and course development.

This article can be found in the category: