Hello! Welcome to the next lesson in your front-end development course.
In our last session, we learned how to use conditional logic (if-else, switch) to make our code execute different actions based on various conditions. This was a huge step towards creating dynamic user experiences.
Today, we'll learn how to package up those logical blocks—and any other set of instructions—into named, reusable units. This lesson covers how to define and call functions with parameters and return values to encapsulate reusable UI logic.
Functions are the fundamental building blocks of any organized program. As a designer, you're used to creating reusable components in Figma. Functions are the code equivalent: you build a piece of logic once and can then use it anywhere you need, ensuring consistency and saving a lot of time.
1. What are Functions and Why Do We Use Them?
Before we dive into the syntax, let's understand the "why". In programming, we have a principle called DRY: Don't Repeat Yourself. If you find yourself writing the same lines of code over and over, that's a signal that you should probably wrap that code in a function.
This article from Tutorial Republic provides a concise summary of the benefits.
Defining and Calling Functions in JavaScript
Let's start with the 'why'. This article clearly explains the advantages of using functions.
Please read the section titled "What is Function?". Focus on the three bullet points that describe the advantages of using functions: reducing repetition, making code easier to maintain, and making it easier to eliminate errors.
2. The Mechanics of a Function: Defining, Calling, and Returning
A function has three main parts to its lifecycle:
- Definition: You create the function and give it a name. This is like creating a component in your design library.
- Calling: You "invoke" or "call" the function by its name to execute the code inside it. This is like dragging an instance of a component onto your canvas.
- Returning: Optionally, a function can give a value back to the code that called it. This is how functions can be used as part of a larger calculation.
This video provides a great hands-on introduction to these core mechanics.
JavaScript Tutorial #6 - Functions & Parameters
This video from DrapsTV demonstrates the basic mechanics of functions. We'll watch the first part to understand how to define a function, call it, and get a value back from it.
Watch from 00:13 to 05:18. Pay attention to: The syntax for creating a function (function functionName() { ... }). The key concept that code inside a function only runs when it's called. How the return keyword sends a value back to where the function was called.
As you saw, the return statement is what makes functions powerful for calculations. When you call a function that returns a value, you can store that value in a variable, just like we did in the video:
// Function Definition
function getNumber() {
return 42;
}
// Calling the function and storing its return value
const myNumber = getNumber();
console.log(myNumber); // Outputs: 42
3. Making Functions Flexible with Parameters
Functions become truly reusable when they can accept input. Imagine a "Button" component in Figma where you can change the label text for each instance. We achieve the same flexibility in code using parameters.
- Parameters are the placeholder variables listed in the function's definition.
- Arguments are the actual values you pass into the function when you call it.
Let's see this in action with the second half of the video.
JavaScript Tutorial #6 - Functions & Parameters
Now let's make our functions more flexible. The same video explains how to use parameters to pass information into a function.
Continue watching from 05:18 to 10:10. Focus on how parameters are defined in the parentheses and how they act as variables that can be used inside the function.
Here's a simple example to reinforce the concept:
// 'name' is the parameter
function createGreeting(name) {
return `Hello, ${name}! Welcome.`;
}
// "Alex" and "Maria" are the arguments
const greetingForAlex = createGreeting("Alex");
const greetingForMaria = createGreeting("Maria");
console.log(greetingForAlex); // Outputs: "Hello, Alex! Welcome."
console.log(greetingForMaria); // Outputs: "Hello, Maria! Welcome."
We wrote the logic for creating a greeting once, and now we can reuse it for any name we want.
4. Your Turn: Encapsulating UI Logic
Now it's time to put all these pieces together and see how functions are used to power a user interface. In this exercise, you will write a few simple calculation functions and then connect them to an input field on a webpage. When the user enters a number, your functions will run and the results will be displayed on the page.
This is the essence of front-end development: writing reusable logic (functions) that responds to user actions.
Function return values - Learn web development | MDN
This exercise from the MDN Web Docs will have you write a few functions and then connect them to an input field on a webpage. This is a perfect example of encapsulating reusable UI logic.
First, make a local copy of the function-library.html file from GitHub as instructed. Then, follow the steps in the section "Implementing function return values". Your task is to: Add the squared(), cubed(), and factorial() functions to the <script> tag. Add the addEventListener code block, which will call your functions whenever the input value changes and display the results in the paragraph. Don't worry about the details of addEventListener for now; we have a whole module on events later. Just understand its role here: it's the 'glue' that runs your code in response to a user action.
Let's break down the most important part of that exercise—the event listener block:
input.addEventListener("change", () => {
const num = parseFloat(input.value); // 1. Get user input
if (isNaN(num)) {
para.textContent = "You need to enter a number!";
} else {
// 2. Call your functions with the input as the argument
para.textContent = `${num} squared is ${squared(num)}. `;
para.textContent += `${num} cubed is ${cubed(num)}. `;
para.textContent += `${num} factorial is ${factorial(num)}. `; // 3. Use the return values to update the UI
}
});
This pattern is fundamental:
- Listen for a user event.
- Get the user's input.
- Call functions with that input.
- Use the functions' return values to update what the user sees.
Conclusion
Excellent work! You've just learned about one of the most important concepts in all of programming. Functions allow you to write clean, organized, and maintainable code, which is essential for building anything beyond a simple script.
Key Takeaways:
- Functions are named, reusable blocks of code that perform a specific task. They help keep your code DRY (Don't Repeat Yourself).
- You define a function with the
functionkeyword and call it using its name followed by parentheses(). - Parameters are variables in a function's definition that act as placeholders for inputs.
- The
returnstatement allows a function to output a value, which can then be used elsewhere in your code. - By combining functions with event listeners, you can create interactive UI logic that responds to user actions.
In our next lesson, we'll explore JavaScript objects. Objects allow us to group related data and functions together into a single entity, which is perfect for modeling real-world things like a user profile, a product listing, or the state of a UI component.
Can't find a good explanation? Sign up and we'll make it for you
Sign up