Introduction to JavaScript Functions

Below is an HTML page with some JavaScript:

<!DOCTYPE html>
  <title>My Page</title>



The line:


is calling (triggering) the alert function that is built into JavaScript. We are passing (sending) the text Hello! to the alert function.


Here's an analogy to help functions make sense.

Let's pretend you hate doing taxes, and you hire an accountant to file your taxes for you. You don't want to worry about all of the little things the accountant must do to complete your taxes; you just want to give your information to the accountant and have it done.

This is why functions are written. There are common tasks we must do often, so we write functions to help us complete those otherwise tedious or complex tasks in a simple way.

Let's write a function for our tax analogy:

function DoMyTaxes(income) {
    return income * .15;


The name of our function is DoMyTaxes, and our parameter (what we hand over to the accountant) is our income (a number). A parameter is a variable created to help pass a value into the function. The braces, { and } simply mark the beginning and end of the function.

If we pretend that the accountant simply calculates what we owe to be 15% of our income, and returns that value to us, we could call the function above as follows: and we will see:

a web page alert dialog with 9000 alerted

The Return Value

So above, the return statement is used to pass a value back to the caller of the function. Going back to our tax analogy, the caller would be you, calling your accountant to have them do your taxes, and the return value would be the number the tax accountant gives to you, to indicate what you owe.

Examples of Functions

  1. How to Split a String in JavaScript

Next: How to Include a JavaScript File


Leave a comment

What color are green eyes? (spam prevention)
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.