What is the purpose of the return operator in a JavaScript function? How do you use it inside a function and what can you do with the return values? Today we’re going to talk about that.
Why return is needed in JavaScript functions
This makes the code more modular. There are many different approaches to writing code. But more often than not, return in a JavaScript function is needed to organize a modular approach.
There are cases when there is no possibility to apply a ternary operator or there is a need to use the same code fragment in several places within one project. In this case it is better to wrap it in a separate function. When it comes to creating a long HTML string, the best option is to store it in a separate function for readability.
Return a string, number or other data type
function renderGreeeting (name) { // Getting an element to render the greeting message let app = document.querySelector('#app'); // Creating a greeting let p = document.createElement('p'); // Create tag p p.textContent = `Hi, ${name}! How are you today?`; // Insert text into the p tag app.appendChild(p); // Inserting tag p into the UI }
Suppose we use some name entered by the user to create some HTML markup in the user interface.
In this example, we could do the following. First, create your own function and put those strings inside. After that you can use return, which will return the element p in the variable. This will allow you to use it later in your code.
function getGreeting (name) { let p = document.createElement('p'); p.textContent = `Hi, ${name}! How are you today?`; return p; } function renderGreeeting (name) { let app = document.querySelector('#app'); // Obtaining the element for rendering the greeting app.appendChild(getGreeting(name)); // Inserting an element into the UI }
Of course, this is a rather simple and even silly example, because return in JavaScript functions returns only one paragraph. But as the amount of code grows, so does the usefulness of this approach.
function getGreeting (name) { // Создаем элементы let wrap = document.createElement('div'); let h1 = document.createElement('h1'); let p = document.createElement('p'); // Adding content h1.textContent = `Hi, ${name}!`; p.textContent = 'How are you today?'; wrap.appendChild(h1); wrap.appendChild(p); return wrap; }
Return of a logical data type with return in JavaScript functions
Return can be very useful when you need to perform more complex checks beyond a simple if … else.
For example, in a web application that displays e-books and courses purchased by users. You need to check if they have purchased a product that has access to Slack’s private workspace. If so, the user sees a button to get the invite link. Otherwise, a message pops up instead.
The “purchase data” object looks something like this:
let data = { guides: [guide1Object, guide2Object, guide3Object, etc], academy: [], otherProducts: [product1, product2] };
Next you need to check if one or more of the following conditions are met:
- the guides key exists in the data, has at least four elements or…
- the academy key exists in the data, has at least one element or…
- the otherProducts key exists in the data and contains one element with the value true
If any of these conditions are met, you can show the user the button.
function renderSlack () { // Getting the application item let app = document.querySelector('#app'); // Doing all the checks if ((data.guides && data.guides.length > 3) || (data.academy && data.academy.length > 0) || data.otherProducts && data.otherProducts.filter(function (product) { return product.slack; }).length > 0) { app.innerHTML = '<button data-slack>Join Slack</button>'; } else { app.innerHTML = '<p>Sorry, you do not have access to Slack.</p>'; } }
This approach is based on too complex logic. This code works, but it is not very readable and hard to maintain. It is very easy to get one of the conditions wrong.
In this case, return in a JavaScript function will help simplify this approach. It will return true if the user has access and false if not. In this case, it runs each condition separately to check, returning true or false.
Yes, this code looks longer. But it is more readable. It is easy to change and control which conditions are checked. And readability is more important than brevity.
function hasSlack () { // Does the customer have at least 4 purchased products if (data.guides && data.guides.length > 3) return true; // Is the customer a member of the online academy if (data.academy && data.academy.length > 0) return true; // Does the customer own another product that has access to Slack let productsWithSlack = data.otherProducts ? data.otherProducts.filter(function (product) { return product.slack; }):[]; if (productsWithSlack) return true; // If none of this is true, there is no access for him return false; }
Now let’s go back to the renderSlack() function. And if the conditions for providing access to Slack ever change, just update the hasSlack() function without changing the rest of the code.
function renderSlack () { let app = document.querySelector('#app'); // Getting the application item // Doing all the checks if (hasSlack()) { app.innerHTML = '<button data-slack>Join Slack</button>'; } else { app.innerHTML = '<p>Sorry, you do not have access to Slack.</p>'; } }
Conclusion
I hope this helps you understand how you can use return in JavaScript functions. This is an organizational tool that allows you to structure your code and make it more readable.