Skip to main content
April 1, 2026Dan Rodney/5 min read

Reusing Code with Functions

Master JavaScript Functions for Reusable Code Development

Key Function Concepts

Function Definition

Create reusable code blocks that perform specific tasks. Functions are defined by you, unlike predefined methods like alert().

Function Calling

Execute functions at desired times using event handlers like onclick. Code inside functions only runs when called.

Parameters & Arguments

Make functions flexible by accepting input values. Parameters define what the function expects, arguments are the actual values passed.

Topics Covered in This JavaScript & jQuery Tutorial:

Master the fundamentals of custom functions: defining reusable code blocks, implementing function calls, and leveraging parameters with arguments for maximum flexibility.

Exercise Preview

functions chart

Exercise Goals

You'll learn to create custom functions that can be reused with different information each time they run, making your code more efficient and maintainable.

Exercise Overview

A function is a self-contained block of reusable code designed to execute specific tasks on demand. Unlike predefined methods such as alert(), which perform fixed operations, functions are entirely custom-built by developers to meet precise requirements. This fundamental programming concept enables code reusability, maintainability, and scalability—core principles that separate professional developers from hobbyists.

Functions can accept different inputs each time they execute, making them incredibly versatile tools for dynamic programming. While methods like alert() can display varying text, they're essentially performing the same predetermined task. Custom functions, however, give you complete control over behavior, logic, and output. In this hands-on exercise, you'll build your first custom function and discover why functions are considered the building blocks of sophisticated JavaScript applications.

Functions vs Methods

FeatureFunctionsMethods
DefinitionDefined by youPredefined
CustomizationFully customizableLimited to existing functionality
ReusabilityReusable with different parametersReusable but fixed behavior
ExampledisplayName()alert()
Recommended: Functions provide greater flexibility and customization for your specific needs.

Defining Functions

Function definition is where the magic begins. You'll create a reusable code block that can be invoked anywhere in your application, transforming repetitive tasks into elegant, maintainable solutions.

  1. Launch your code editor and ensure you have a clean workspace by closing any currently open files.
  2. Open a new file using Cmd–O (Mac) or Ctrl–O (Windows).
  3. Navigate to Desktop > Class Files > yourname-JavaScript jQuery Class > Functions and locate your project directory.
  4. Double-click index.html to open the base template file.
  5. Insert the following script block before the closing </head> tag (typically line 6). This placement ensures your JavaScript loads before the page content renders:

    <title>Functions</title>
       <script>
    
       </script>
    </head>
  6. Within the script tags, define your first custom function by adding this code block:

    <script>
       function displayName() {
          alert('Dan Rodney');
       }
    </script>
  7. Let's analyze this function declaration: displayName() is the function identifier, while the curly braces { } contain the executable code block. When invoked, this function triggers an alert() displaying "Dan Rodney". Remember that JavaScript enforces strict case sensitivity—the capital "N" in displayName() must be matched exactly when calling this function, or your code will fail.
  8. Save your file to preserve these changes.
  9. Preview index.html in your browser using one of these methods:

    Visual Studio Code users: With the "open in browser" extension installed, press Option–B (Mac) or Alt–B (Windows) for instant browser preview.

    Alternative method: In your browser, press Cmd–O (Mac) or Ctrl–O (Windows), then navigate to your yourname-JavaScript jQuery Class > Functions directory to locate index.html.

  10. Notice that the page loads without any alerts appearing. This behavior demonstrates a crucial concept: functions contain dormant code that executes only when explicitly called. Simply defining a function doesn't trigger its execution.
  11. Keep the browser tab open—you'll be refreshing it frequently to test your code changes as we progress through the next section.

Function Definition Process

1

Add Script Tags

Place script tags in the head section before the closing /head tag to contain your JavaScript code.

2

Declare Function

Use the function keyword followed by a name and parentheses. Function names are case-sensitive in JavaScript.

3

Define Function Body

Place the code to be executed between curly braces. This code will only run when the function is called.

Case Sensitivity Important

JavaScript is case-sensitive. Function names like displayName() must match exactly when called later, or your code will break.

Calling Functions

Function invocation transforms static code into dynamic behavior. You'll now learn how to trigger your custom function through user interactions, bringing your code to life.

  1. Return to your code editor to implement the function call mechanism.
  2. Create a user interface element that will trigger your function. Add this button element within the body section:

    <body>
       <button>Show a Name</button>
    </body>
  3. HTML elements are passive by default and don't respond to user interactions without explicit instructions. To make your button responsive, add the onclick event handler that connects user clicks to your JavaScript function:

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

    Professional insight: The onclick attribute creates an event listener that waits for click events. When triggered, it executes the specified JavaScript code. This inline event handling approach works well for simple demonstrations, though modern applications typically use more sophisticated event binding methods for better code organization and maintainability.

  4. Save your file and refresh the browser to test your implementation.
  5. Click the Show a Name button to trigger your function. You should see an alert displaying "Dan Rodney". Click OK to dismiss the alert, then click the button again to verify the function can be executed repeatedly. This demonstrates the fundamental power of functions: write once, use infinitely.
Code inside functions is only executed when the function is called.
This is why nothing happens when you first preview the HTML file - the function exists but hasn't been triggered yet.

Implementing Function Calls

1

Create HTML Element

Add a button or other interactive element in the body section that users can interact with.

2

Add Event Handler

Use the onclick attribute to tell the element to listen for click events and specify which function to execute.

3

Test Functionality

Save and preview in browser to verify the function executes when the element is clicked.

Defining Parameters & Passing Arguments

Static functions have limited utility in real-world applications. Parameters and arguments transform rigid functions into flexible, data-driven tools that adapt to different scenarios—the hallmark of professional JavaScript development.

  1. A hardcoded alert severely limits functionality. Let's evolve your function to accept dynamic data inputs, making it truly reusable across different contexts.
  2. Modify your function signature to accept parameters—placeholders for data that will be provided when the function is called:

    function displayName(firstName, lastName) {
       alert('Dan Rodney');
    }
  3. Update the alert statement to utilize these parameters through string concatenation:

    function displayName(firstName, lastName) {
       alert(firstName + ' ' + lastName);
    }
  4. Now modify your button to pass arguments—the actual data values—to your parameterized function:

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

    Critical syntax note: The single quotes around 'Dan' and 'Rodney' are essential for proper HTML/JavaScript interaction. Since HTML requires double quotes for the onclick attribute value, using double quotes for the string literals would terminate the attribute prematurely, breaking your code. This quote nesting is a fundamental web development practice.

  5. Save your changes and test the functionality in your browser.
  6. Click the Show a Name button. The alert should still display "Dan Rodney", but now this data flows dynamically through the parameter system rather than being hardcoded.
  7. Dismiss the alert and return to your code editor to explore the true power of parameterized functions.
  8. Demonstrate function versatility by duplicating your button element:

    <button onclick="displayName('Dan', 'Rodney');">Show a Name</button>
    <button onclick="displayName('Dan', 'Rodney');">Show a Name</button>
    </body>
  9. Customize the second button to showcase different data processing with the same underlying function:

    <button onclick="displayName('Dan', 'Rodney');">Show a Name</button>
    <button onclick="displayName('Trevor', 'Sammis');">Another Name</button>
  10. Save your file and refresh the browser to test both buttons.
  11. Click each button to verify they produce different outputs using identical function logic. This exemplifies the elegance of parameterized functions: one definition, infinite possibilities.

    Reference materials: Complete code examples are available in Desktop > Class Files > yourname-JavaScript jQuery Class > Done-Files > Functions for comparison and troubleshooting.

Parameters vs Arguments

FeatureParametersArguments
DefinitionVariables in function definitionActual values passed to function
LocationInside function parenthesesInside function call parentheses
PurposeAsk for informationProvide specific information
ExamplefirstName, lastName'Dan', 'Rodney'
Recommended: Parameters make functions flexible by allowing different inputs each time they're called.
Quote Usage in HTML

Use single quotes around string arguments inside HTML attributes that use double quotes. This prevents the HTML parser from ending the attribute value prematurely.

Function Implementation Checklist

0/6

Key Takeaways

1Functions are groups of reusable code that perform specific tasks and can be executed at desired times
2Unlike predefined methods like alert(), functions are completely customizable and defined by the developer
3JavaScript is case-sensitive, so function names must match exactly between definition and calling
4Code inside functions only executes when the function is called, not when it's defined
5Event handlers like onclick connect HTML elements to JavaScript functions for user interaction
6Parameters make functions flexible by allowing them to accept different input values each time they're called
7Arguments are the actual values passed to functions, while parameters are the variables that receive those values
8When using string arguments in HTML attributes, use single quotes to avoid conflicts with the attribute's double quotes
9Functions promote code reusability and maintainability by eliminating the need to repeat similar code blocks

RELATED ARTICLES