If youโve ever dipped your toes into JavaScript, youโve probably run into functions and wondered, โOkay, this does somethingโฆ but how do I actually get something back from it?โ Thatโs exactly where return values come into play. As someone who has spent years guiding beginners and building practical coding projects, I can confidently say that understanding return values is one of the most underrated skills in JavaScript. Once you grasp it, your code not only works betterโit makes more sense and is easier to debug.
In this guide, weโll explore what return values are, how they differ from other ways of checking results like console.log, common mistakes to avoid, and practical examples you can start using today. Along the way, Iโll also drop some handy links to other coding concepts like arrays and functions so you can deepen your understanding as you go.
Introduction: Why Return Values Matter in JavaScript
Return values are the lifeblood of functions. Think of a function as a coffee machine. You put in some coffee beans and water, press a button, and you get a cup of coffee. In programming, the coffee machine is your function, the coffee beans and water are the input parameters, and the cup of coffee is the return value. Without a return value, your function might run, do its internal magic, but you get nothing out of itโlike a coffee machine that grinds beans but doesnโt pour coffee into a cup.
Understanding how return values work helps you:
- Build more predictable code: Youโll know exactly what each function outputs.
- Chain functions together: Using one functionโs output as another functionโs input becomes seamless.
- Avoid common beginner mistakes: Like ignoring return values or accidentally returning the wrong type.
For beginners, return values might seem a bit abstract at first. But with simple examples and practice, it becomes second nature, just like learning JavaScript basics.
Who This Guide Is For
If youโre new to JavaScript, this guide is perfect. Even if youโve been coding for a while but have ignored return values, youโll find these examples eye-opening. By the end of this article, youโll feel confident using return values in your mini projects and everyday code.
How Understanding Return Values Improves Your Code
Imagine youโre writing a program that calculates the total price of items in a shopping cart. You could log values with console.log, but if you donโt return the result, other parts of your program canโt use it. Return values make your code modular and reusable.
For example, knowing how return values work allows you to:
- Create functions that can be used in multiple programs.
- Debug complex code more easily, using return outputs as checkpoints.
- Avoid unnecessary variables, keeping your code clean and readable.
What Are Return Values in JavaScript?
At its core, a return value is simply the output of a function. When a function is executed, it can โreturnโ somethingโanything from numbers, strings, booleans, objects, arrays, or even another function. Without a return, the function will default to returning undefined.
Definition and Concept
In JavaScript, you define a return value with the return keyword:
function add(a, b) {
return a + b;
}
Here, a + b is the return value. If you call add(2, 3), the function will output 5. But noticeโif you simply wrote console.log(a + b) inside the function instead of return, the function wouldnโt give anything back to the code that called it.
For beginners, this is a common source of confusion. Check out our console basics guide for more insight on when to use console.log versus return.
Return Values vs. Console.log: Whatโs the Difference?
A lot of new coders use console.log to see whatโs happening inside a function. Thatโs fine for debugging, but itโs not a replacement for return values.
Think of it like this:
console.logis a sticky note. It tells you whatโs happening but disappears once the program moves on.returnis like sending a message to another part of your codeโit actually delivers a result that other functions or variables can use.
Example Comparison
function multiply(a, b) {
console.log(a * b); // just prints 15
}
function multiplyWithReturn(a, b) {
return a * b; // can be stored in a variable
}
const result = multiplyWithReturn(3, 5);
console.log(result); // prints 15
See the difference? Only the function with return allows you to store and reuse the result. Without it, youโre limited to just looking at the value once.
If you want a deeper dive into how function examples use return values, weโve got some practical demonstrations that beginners find super helpful.
Functions and Return Values: A Deep Dive
Functions are the building blocks of JavaScript. Once you understand how return values interact with functions, your coding world opens up.
What Happens When a Function Returns Something
When you use the return keyword, the function sends the value back to where it was called. This means you can:
- Assign the result to a variable.
- Pass it to another function.
- Use it directly in expressions.
Example:
function greet(name) {
return "Hello, " + name + "!";
}
const message = greet("Widya");
console.log(message); // "Hello, Widya!"
Without return, you couldnโt store or reuse "Hello, Widya!".
Implicit vs Explicit Returns
JavaScript has a handy shortcut with arrow functions. Some arrow functions can return a value implicitly, without using the return keyword.
const square = x => x * x;
console.log(square(4)); // 16
Notice how x * x is returned automatically? Thatโs an implicit return. If you use curly braces {}, you must explicitly write return.
const square = x => {
return x * x;
};
This distinction becomes really useful when writing concise JavaScript code examples.
Why Every Function Should Consider a Return Value
Even if your function seems simple, think about the future. Will other parts of your code need to use this result? Will you want to chain multiple functions together later?
- A function without a return canโt be used as part of a larger calculation.
- Returning a meaningful value makes your code predictable and testable.
- It encourages writing functions that do one thing and one thing only, a key clean code principle.
Common Return Value Mistakes Beginners Make
Even seasoned coders have made these mistakes at some point. Beginners especially run into these issues because return values are invisibleโyou canโt see them unless you store or use them. Letโs break down the most common pitfalls.
Not Returning Anything by Accident
One of the most frequent mistakes is forgetting to use the return keyword altogether.
function addNumbers(a, b) {
a + b; // forgot return
}
const result = addNumbers(5, 10);
console.log(result); // undefined
Notice how result prints undefined? The function did the addition, but because thereโs no return, nothing comes back. Beginners often rely on console.log to see results and miss this crucial step.
Pro Tip: Always ask yourself, โDo I want this function to give something back?โ If yes, use return.
Returning the Wrong Type
JavaScript is flexible with data types, which is greatโbut also a trap for beginners. You might intend to return a number but accidentally return a string.
function getAge(yearBorn) {
return "2026" - yearBorn; // correct output, but mixing string and number
}
console.log(getAge(2000)); // 26, works fine but risky in calculations
Mixing types can lead to subtle bugs. For serious projects, understanding data types is essential.
Ignoring the Return Value in Code Logic
Sometimes beginners create functions, return values, and then completely ignore them.
function calculateTip(total) {
return total * 0.15;
}
calculateTip(100); // return value not stored or used
Even though the function works, the program doesnโt do anything useful. You might as well have not returned anything.
Solution: Assign the return value to a variable or use it directly in expressions.
const tip = calculateTip(100);
console.log(`Your tip is $${tip}`); // Your tip is $15
Practical Examples of Return Values
Now that weโve seen the common mistakes, letโs look at some real-life examples. These will help solidify your understanding.
Mathematical Operations
Return values are often used in calculations. Think of them as the backbone of programs like calculators or shopping cart apps.
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
console.log(add(10, 5)); // 15
console.log(subtract(10, 5)); // 5
Notice how these functions can be used anywhere you need the value, stored in a variable, or even passed to another function.
Want a deeper dive into mathematical functions? Check out our JavaScript function examples guide.
String Manipulations
Return values are essential when working with strings. Whether youโre formatting names, concatenating messages, or extracting parts of a string, return makes it reusable.
function greetUser(firstName, lastName) {
return `Hello, ${firstName} ${lastName}! Welcome!`;
}
console.log(greetUser("Widya", "Developer")); // Hello, Widya Developer! Welcome!
You can even chain string-returning functions for more complex outputs:
function makeExcited(message) {
return message.toUpperCase() + "!!!";
}
console.log(makeExcited(greetUser("Widya", "Developer")));
// HELLO, WIDYA DEVELOPER! WELCOME!!!!
This is a perfect example of why understanding functions logic is so crucial.
Boolean Checks and Conditions
Return values are not limited to numbers or strings. Functions can return booleans, which are great for conditional checks.
function isAdult(age) {
return age >= 18;
}
console.log(isAdult(20)); // true
console.log(isAdult(15)); // false
These boolean returns can be plugged directly into if-else statements, loops, or even used in more complex logical operations.
Advanced Tips: Using Return Values Efficiently
Once youโre comfortable with basic return values, itโs time to level up. Proper use of return values can make your code cleaner, more reusable, and easier to debug.
Chaining Functions Using Return Values
Chaining is when the output of one function becomes the input of another. This is incredibly powerful when building complex programs.
function double(number) {
return number * 2;
}
function square(number) {
return number * number;
}
const result = square(double(5));
console.log(result); // 100
Here, double(5) returns 10, which is immediately passed to square. You can even create multiple layers of transformations in your code, which is common in JavaScript projects.
Using Return Values for Debugging
Return values arenโt just for final outputโtheyโre invaluable for debugging. Instead of scattering console.log statements everywhere, return intermediate results and check them.
function processNumber(number) {
const doubled = number * 2;
const squared = doubled * doubled;
return squared;
}
console.log(processNumber(3)); // 36
Returning values at each step can help pinpoint where your logic might be off. For more debugging tips, visit our debugging guide.
Returning Objects vs. Primitives
A common advanced scenario is returning complex data like objects or arrays. This allows you to pass around structured data rather than just numbers or strings.
function createUser(name, age) {
return {
name: name,
age: age,
isAdult: age >= 18
};
}
const user = createUser("Widya", 25);
console.log(user.name); // Widya
console.log(user.isAdult); // true
Returning structured objects is a key skill in real-world JavaScript, especially when handling data from APIs or user input.’
Best Practices for Return Values in JavaScript
Now that you understand the basics and have seen practical examples, letโs explore some best practices for using return values efficiently. Following these tips will make your code cleaner, more readable, and less error-prone.
Always Return Something Meaningful
If a function is meant to calculate, transform, or check something, always make sure it returns a meaningful value. Avoid functions that just โdo stuffโ without giving anything backโunless your functionโs purpose is purely procedural (like logging or modifying the DOM).
function calculateDiscount(price, discountPercent) {
return price - (price * discountPercent / 100);
}
console.log(calculateDiscount(100, 15)); // 85
Here, the function directly returns the final discounted price, which can be reused anywhere else in your program.
Keep Return Values Consistent
Mixing return types can confuse your code and anyone reading it later. For example, donโt return a number sometimes and a string other times. This is especially important in beginner JavaScript practice exercises.
function formatScore(score) {
if (score >= 0) {
return score; // number
} else {
return 0; // also number, not string
}
}
Consistency ensures predictable code behavior.
Leverage Return Values in Mini Projects
Mini projects are an excellent way to internalize return values. Here are a few ideas:
- Calculator App โ Functions like add, subtract, multiply, divide all return results.
- User Profile Generator โ Return an object with user data.
- Boolean Checkers โ Functions return true/false based on user input.
These projects can be built step by step using our mini project guides to reinforce learning.
Avoid Unnecessary Variables
Sometimes beginners create extra variables to store temporary results before returning them. While not always wrong, often itโs cleaner to return the result directly.
// Instead of this:
function sum(a, b) {
const result = a + b;
return result;
}
// Do this:
function sum(a, b) {
return a + b;
}
This makes your code more concise and readable, aligning with clean code principles.
Test Return Values Thoroughly
Testing isnโt just for big projects. Even small functions can break if they return unexpected values. Create simple test cases to ensure your function always returns what you expect.
console.assert(calculateDiscount(200, 25) === 150, "Discount calculation failed!");
This approach saves headaches later, especially when combining multiple functions.
Mini Project Example: Simple Shopping Cart
Letโs put return values into practice with a mini project example: a simple shopping cart.
function addItem(cart, item, price) {
return [...cart, { item, price }];
}
function calculateTotal(cart) {
return cart.reduce((total, product) => total + product.price, 0);
}
let cart = [];
cart = addItem(cart, "Book", 15);
cart = addItem(cart, "Pen", 5);
console.log(calculateTotal(cart)); // 20
Here you can see:
addItemreturns a new cart array, preserving immutability.calculateTotalreturns the sum of all prices.- Both functions can be reused and combined effortlessly.
You can explore more practice tools to simulate similar scenarios and reinforce your learning.
Conclusion
Return values are the heartbeat of JavaScript functions. Without them, functions are limited to running code without producing usable results. By mastering return values, you:
- Gain the ability to write reusable and modular functions.
- Avoid common beginner mistakes like forgetting to return or returning inconsistent types.
- Improve debugging, readability, and code flow.
Remember, even simple examples like mathematical operations, string manipulations, or boolean checks can become powerful building blocks in larger projects once you start returning and reusing values correctly.
Mastering return values may seem subtle, but itโs a skill that dramatically improves your coding efficiency, helping you move from a beginner to a confident JavaScript developer.
FAQs
1. What is a return value in JavaScript?
A return value is the output of a function that is sent back to the place where the function was called. Without it, the function returns undefined by default.
2. Can a function return multiple values?
Not directly, but you can return an array or an object containing multiple values.
3. What happens if I forget the return keyword?
The function will execute its code but return undefined, which means you canโt use the output in further calculations or logic.
4. What types of values can be returned?
Functions can return numbers, strings, booleans, arrays, objects, other functions, or even null/undefined.
5. How do return values differ from console.log?console.log only prints the value to the console. Return values send data back to the calling code for reuse.
6. Are return values always necessary?
No. Functions that perform side effects like logging or updating the UI may not need return values. But in most reusable logic, they are essential.
7. How can return values improve debugging?
By returning intermediate results instead of logging them, you can test function outputs and identify logic errors more reliably.

Iโm the tech educator behind truthreado.com, specializing in JavaScript Basics, beginner-friendly coding tutorials, and web development concepts. I share practical lessons, clear explanations, and hands-on examples to help readers build strong programming foundations.
