Reusing Code with Functions

Free JavaScript & jQuery Tutorial

This exercise is excerpted from Noble Desktop’s past JavaScript training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.

Note: These materials are provided to give prospective students a sense of how we structure our class exercises and supplementary materials. During the course, you will get access to the accompanying class files, live instructor demonstrations, and hands-on instruction.

Topics covered in this JavaScript & jQuery tutorial:

Defining functions, Calling functions, Defining parameters & passing arguments

Exercise Preview

functions chart

Exercise Overview

A function is a group of reusable code that performs a specific task (or tasks) at a desired time. The function can be run repetitively, potentially using different information each time it runs. Methods such as alert() are similar to functions, but they’re predefined. We can do multiple alerts with varying text, but it’s essentially doing the same task again. Functions, however, are defined by you. You decide what they will do, so in this exercise, you’ll learn how to make a custom function.

Defining Functions

  1. Open your code editor if it isn’t already open.
  2. Close any files you may have open.
  3. In your code editor, hit Cmd–O (Mac) or Ctrl–O (Windows) to open a file.
  4. Navigate to the Desktop and go into the Class Files folder, then yourname-JavaScript jQuery Class folder, then Functions.
  5. Double–click on index.html to open it.
  6. Add the following bold code before the closing </head> tag (on line 6):

       <title>Functions</title>
       <script>
    
       </script>
    </head>
    
  7. In the script tag, add the following bold code to define a function:

    <script>
       function displayName() {
          alert('Dan Rodney');
       }
    </script>
    
  8. Let’s break this down. We just declared a function named displayName(). The function will perform everything between the curly braces { }, which is to alert() the name Dan Rodney. Keep in mind that JavaScript is case-sensitive. We used a capital N for our function’s name, displayName(). Later we’ll need to match that case or else things could break.
  9. Save the file.
  10. Preview index.html (from the Functions folder) in a browser.

    NOTE: If you’re using Visual Studio Code with the open in browser extension installed, hit Option–B (Mac) or Alt–B (Windows) to open the saved HTML document in a browser.

    If your using another code editor or don’t have that keystroke set up, you can open the pages from your browser window to preview it. In your browser, you can hit Cmd–O (Mac) or Ctrl–O (Windows) to open index.html. Navigate to the yourname-JavaScript jQuery Class folder and then Functions to find the file.

  11. Notice that nothing happens. Code inside functions is only executed when the function is called. Let’s see how to do that.
  12. Leave index.html open in the browser, so you can reload the page to see the changes you make in your code.

Calling Functions

  1. Switch back to your code editor.
  2. We want to run this function when the user clicks a button. In the body section, type the following text in bold:

    <body>
       <button>Show a Name</button>
    </body>
    
  3. Now we need the button to “talk” to JavaScript. HTML elements do not listen for events by default. Instead, we need to tell them to listen for events (such as the click of a button). Here we’ll add the onclick attribute and set it equal to the function we want to trigger. Add the following bold code:

    <body>
       <button onclick="displayName();">Show a Name</button>
    </body>
    

    NOTE: Adding onclick will tell the button to listen for a click event, and only execute the code within the function at that time. The onclick event handler is one of many, and we’ll see more in the coming exercises.

  4. Now when the user clicks the button, our displayName() function will run. Let’s check it out. Save the file and preview in a browser.

  5. Click the Show a Name button. An alert should appear with the name Dan Rodney in it. Click OK to close the alert, then click the button again to see that the alert appears again. We’re reusing the code!

Defining Parameters & Passing Arguments

  1. An alert that always displays the same thing isn’t very flexible. Let’s make it work with different names. Switch back to your code editor.

  2. In order to make a function reusable, we give it parameters. Then when we call the function, we can pass information into it. Around line 7 add these two parameters to the function:

    function displayName(firstName, lastName) {
       alert('Dan Rodney');
    }
    
  3. Now edit the alert to use those parameters:

    function displayName(firstName, lastName) {
       alert(firstName + ' ' + lastName);
    }
    
  4. While a function’s parameters ask for information, the pieces of info we pass to it are called arguments. Below, change the button to pass the arguments 'Dan' and 'Rodney' to the displayName() function.

    <button onclick="displayName('Dan','Rodney');">Show a Name</button>
    

    IMPORTANT! Notice that Dan and Rodney are surrounded by single quotes, not double quotes. JavaScript doesn’t care which are used, but HTML does. For HTML, the double quotes must wrap the onclick attribute’s value. If we used double quotes, HTML would think the onclick attribute would end too early and things would break.

  5. Save and preview index.html in a browser.
  6. Click the Show a Name button. Again, it should alert Dan Rodney, but this time those names were passed into the function.
  7. Click OK to close the alert.
  8. Switch back to your code editor.
  9. Make a second button by copying and pasting the first one.

       <button onclick="displayName('Dan','Rodney');">Show a Name</button>
       <button onclick="displayName('Dan','Rodney');">Show a Name</button>
    </body>
    
  10. Alter the second button so it looks as shown below:

    <button onclick="displayName('Dan','Rodney');">Show a Name</button>
    <button onclick="displayName('Trevor','Sammis');">Another Name</button>
    
  11. Save and preview the file in a browser.
  12. Click each of the buttons. They should give you two different alerts. That is one flexible function!

    NOTE: If you want to refer to our final code example, go to Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Functions.

How to Learn Coding

Master coding with hands-on training. Learning how to code in JavaScript, Python, and other popular languages can pave the way to a job in tech, such as web development, data science & analytics, or software engineering.

Yelp Facebook LinkedIn YouTube Twitter Instagram