Skip to main content
March 23, 2026Dan Rodney/7 min read

Functions & Event Handlers

Master JavaScript Functions and Event Handling Fundamentals

Core JavaScript Concepts

Function Definition

Learn to create reusable code blocks that perform specific tasks. Functions are the building blocks of JavaScript applications.

Event Handlers

Discover how to make web pages interactive by responding to user actions like clicks and form submissions.

Parameters & Arguments

Master the art of passing data to functions to make them flexible and reusable across different scenarios.

Topics Covered in This JavaScript Tutorial:

Defining & Calling Functions, Defining Parameters & Passing Arguments, Using an Event Listener

Exercise Preview

functions chart

Exercise Overview

In this exercise, you'll master one of JavaScript's most powerful features: functions. A function is a reusable block of code designed to perform specific tasks when called upon. Think of functions as the building blocks of efficient programming—they eliminate redundancy, improve maintainability, and make your code more modular and testable.

While you've already used built-in methods like alert(), functions give you the power to create custom solutions tailored to your specific needs. Unlike predefined methods, functions are entirely under your control—you define their behavior, parameters, and return values. This flexibility makes functions indispensable for creating scalable, professional web applications.

Functions vs Methods

While methods like alert() are predefined by JavaScript, functions are custom code blocks that you define to perform specific tasks. This gives you complete control over what your code does.

Defining Functions

Let's start by creating your first custom function. We'll build from a simple example to more complex implementations that demonstrate real-world programming patterns.

  1. For the first part of this exercise we'll be working with the Functions folder located in Desktop > Class Files > JavaScript Class. Open that folder in your code editor if it allows you to (like Visual Studio Code does).
  2. In your code editor, open index.html from the Functions folder.
  3. Add the following bold code before the closing </head> tag:

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

    <script>
       function displayName() {}
    </script>
  5. In the function's curly braces, add the following bold code which defines what the function will execute when called:

    function displayName() {
       alert('Dan Rodney');
    }

    Let's examine the anatomy of this function declaration. We've created a function named displayName()—notice the descriptive name that includes a verb, following JavaScript naming conventions. This makes your code self-documenting and easier for other developers (including future you) to understand.

    The function body, enclosed in curly braces { }, contains the code that executes when the function is called. Currently, it displays an alert with the name Dan Rodney. Remember that JavaScript is case-sensitive, so our function name displayName() must be referenced exactly as written—inconsistent casing is a common source of runtime errors.

  6. Save the file.
  7. Preview index.html (from the Functions folder) in a web browser.
  8. Notice that nothing happens. This demonstrates a crucial concept: function code is only executed when explicitly called. Simply defining a function doesn't run it—this separation of definition and execution is what makes functions so powerful for creating reusable code.

    NOTE: Leave this page open in the browser, so you can reload it to see the changes you make in the code.

Creating Your First Function

1

Open Script Tag

Add script tags in the head section of your HTML document to contain your JavaScript code.

2

Declare Function

Use the function keyword followed by a descriptive name with parentheses and curly braces.

3

Add Function Body

Write the code that will execute when the function is called inside the curly braces.

Function Naming Best Practice

Include a verb in your function name because functions perform actions. Use camelCase and be descriptive about what the function does.

Calling Functions

Now that you've defined a function, let's explore different ways to invoke it. Understanding when and how to call functions is essential for creating interactive user experiences.

  1. Switch back to your code editor.
  2. First, let's see immediate function execution. While we'll eventually trigger this function through user interaction, let's temporarily call it on page load to understand the mechanism:

    <script>
       function displayName() {
          alert('Dan Rodney');
       }
       displayName();
    </script>
  3. Save and preview the file in a browser.

    The alert displays immediately when the page loads, demonstrating direct function invocation.

  4. Click OK and return to your code editor.
  5. Remove the immediate function call to prepare for event-driven execution:

    <script>
       function displayName() {
          alert('Dan Rodney');
       }
    </script>
  6. Now let's create a user interface element to trigger our function. In the body section, add the following button:

    <body>
       <button>Show a Name</button>
    </body>
  7. To make the button interactive, we need to establish event handling. HTML elements don't automatically respond to user interactions—we must explicitly configure them to listen for specific events. Add the onclick attribute to connect the button to our function:

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

    NOTE: The onclick attribute creates an event listener that waits for click events. This approach, while simple, embeds JavaScript in HTML. Later in this tutorial, we'll explore more sophisticated event handling techniques that separate concerns more effectively.

  8. Test your event-driven function by saving the file and previewing in a browser:

    • Click the Show a Name button. An alert should display "Dan Rodney".
    • Click OK to close the alert.
    • Click the button again to confirm the function executes repeatedly. This demonstrates code reusability—a core benefit of functions.
    • Click OK again.
  9. Switch back to your code editor.

Function Execution Methods

FeatureImmediate CallEvent-Based Call
Execution TimePage LoadUser Action
Code LocationJavaScript SectionHTML Element
User ControlNoneFull Control
ReusabilityOnce OnlyMultiple Times
Recommended: Event-based calls provide better user experience and code reusability.

Defining Parameters & Passing Arguments

While our basic function works, it's limited by its hardcoded output. Professional JavaScript development requires flexible, configurable functions. Let's enhance our function with parameters—placeholders that accept different values each time the function is called.

  1. A function that always produces the same output severely limits its utility. Let's add parameters to make it dynamic and reusable across different scenarios:

    function displayName(firstName, lastName) {
       alert('Dan Rodney');
    }
  2. Now modify the alert to utilize those parameters through string concatenation:

    function displayName(firstName, lastName) {
       alert(firstName + ' ' + lastName);
    }
  3. Understanding the distinction between parameters and arguments is crucial: parameters are the variables defined in the function declaration, while arguments are the actual values passed when calling the function. Update the button to pass specific arguments:

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

    IMPORTANT! Notice that the arguments are enclosed in single quotes, not double quotes. This follows a critical HTML/JavaScript integration rule: since the entire onclick attribute value must be wrapped in double quotes, any string literals within must use single quotes to avoid prematurely terminating the attribute value.

  4. Save and preview index.html in a browser:

    • Click the Show a Name button. The alert should display "Dan Rodney", but now this data is dynamically passed into the function rather than hardcoded.
    • Click OK to close the alert.
  5. Switch back to your code editor.
  6. Let's demonstrate the true power of parameterized functions by creating multiple buttons with different arguments:

    <button onclick="displayName('Dan', 'Rodney');">Show a Name</button>
       <button onclick="displayName('Dan', 'Rodney');">Show a Name</button>
    </body>
  7. Customize the second button to demonstrate function flexibility:

    <button onclick="displayName('Dan', 'Rodney');">Show a Name</button>
    <button onclick="displayName('Trevor', 'Smith');">Another Name</button>
  8. Save and preview the file in a browser:

    • Click each button to see how a single function definition can produce different outputs based on the arguments passed. This demonstrates the DRY principle (Don't Repeat Yourself)—a fundamental concept in professional software development.
Quote Usage in HTML

When using onclick attributes, wrap the attribute value in double quotes and any string arguments in single quotes to prevent HTML parsing errors.

Parameters vs Arguments

Parameters

Variables listed in the function definition that act as placeholders for incoming data. They define what information the function expects.

Arguments

Actual values passed to the function when it's called. These values fill the parameter placeholders during execution.

Product Chooser: Functions & Event Handlers

Now let's apply these concepts to a more realistic scenario. We'll build an interactive product interface that demonstrates how functions integrate with DOM manipulation—a pattern you'll use constantly in modern web development.

  1. In your code editor, close any files you may have open.
  2. For the rest of this exercise we'll be working with the Product-Chooser-Function folder located in Desktop > Class Files > JavaScript Class. Open that folder in your code editor if it allows you to (like Visual Studio Code does).
  3. In your code editor, open product.html from the Product-Chooser-Function folder.
  4. Preview product.html in a web browser.

    This file contains the foundation from a previous exercise—currently, it automatically changes the product photo and applies styling to a button when the page loads. We'll refactor this into an event-driven system using functions, creating a more interactive and user-controlled experience.

  5. Back in your code editor, encapsulate the existing functionality within a function:

    <script>
       let productPhoto = document.getElementById('product-photo');
       let colorButton = document.getElementById('red');
    
       function changeColor() {
          productPhoto.src = 'img/chair-red.jpg';
          colorButton.classList.add('selected');
       }
    </script>
  6. Now we'll implement a more sophisticated event handling approach. Instead of mixing JavaScript with HTML attributes, we'll use the addEventListener method to maintain cleaner separation of concerns:

    colorButton.classList.add('selected');
       }
       colorButton.addEventListener();
    </script>

    NOTE: This approach, known as unobtrusive JavaScript, keeps all JavaScript code in one place rather than scattered throughout HTML attributes. This makes code easier to maintain, debug, and scale—essential practices in professional development environments.

  7. Configure the event listener to watch for click events and execute our function:

    colorButton.addEventListener('click', changeColor);

    NOTE: Observe that the function name changeColor is passed without parentheses. This passes a reference to the function rather than immediately executing it. The event listener will invoke the function only when the specified event occurs—this lazy execution pattern is fundamental to event-driven programming.

  8. Save and preview the file in a browser.
  9. Click the red button to trigger the color change and visual feedback. Notice how the interaction feels more responsive and intentional compared to automatic execution on page load.

    While our current implementation works for a single button, real-world applications require scalable solutions. To extend this functionality across multiple color options, you'll need to work with arrays and iteration patterns—concepts we'll explore in upcoming exercises. This progression from simple functions to complex interactive systems mirrors the learning path of professional JavaScript developers.

Unobtrusive JavaScript Approach

Pros
Separates JavaScript code from HTML markup
Keeps all JS code together for easier maintenance
Improves code organization and readability
Better debugging capabilities
Follows modern web development standards
Cons
Slightly more complex initial setup
Requires understanding of event listener syntax
Event Listener Function Reference

When passing a function to addEventListener, use the function name without parentheses. This refers to the function without executing it immediately.

Key Takeaways

1Functions are reusable code blocks that perform specific tasks and can be called multiple times throughout your program.
2Function names should include verbs and use camelCase for clarity and JavaScript convention compliance.
3Code inside functions only executes when the function is called, not when it's defined.
4Parameters make functions flexible by allowing different data to be passed in each time the function runs.
5Event handlers connect user interactions to JavaScript functions using onclick attributes or addEventListener methods.
6Unobtrusive JavaScript separates code from HTML, improving maintainability and following modern development practices.
7When using onclick in HTML, wrap attribute values in double quotes and string arguments in single quotes.
8The addEventListener method provides more control and better code organization than inline event handlers.

RELATED ARTICLES