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.
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.
Functions vs Methods
| Feature | Functions | Methods |
|---|---|---|
| Definition | Defined by you | Predefined |
| Customization | Fully customizable | Limited to existing functionality |
| Reusability | Reusable with different parameters | Reusable but fixed behavior |
| Example | displayName() | alert() |
Function Definition Process
Add Script Tags
Place script tags in the head section before the closing /head tag to contain your JavaScript code.
Declare Function
Use the function keyword followed by a name and parentheses. Function names are case-sensitive in JavaScript.
Define Function Body
Place the code to be executed between curly braces. This code will only run when the function is called.
JavaScript is case-sensitive. Function names like displayName() must match exactly when called later, or your code will break.
Code inside functions is only executed when the function is called.
Implementing Function Calls
Create HTML Element
Add a button or other interactive element in the body section that users can interact with.
Add Event Handler
Use the onclick attribute to tell the element to listen for click events and specify which function to execute.
Test Functionality
Save and preview in browser to verify the function executes when the element is clicked.
Parameters vs Arguments
| Feature | Parameters | Arguments |
|---|---|---|
| Definition | Variables in function definition | Actual values passed to function |
| Location | Inside function parentheses | Inside function call parentheses |
| Purpose | Ask for information | Provide specific information |
| Example | firstName, lastName | 'Dan', 'Rodney' |
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
Use camelCase naming convention
Parameters make functions reusable with different data
Write code that performs the desired task
Buttons or other elements trigger function execution
onclick and other events connect HTML to JavaScript
Verify function works with various input values
Key Takeaways
