Understanding the Return Statement in JavaScript Functions (With Examples)

0

 

what is return keyword in javascript


Ever wondered why some JavaScript functions give you back a result while others don’t? The answer lies in the magical javascript return keyword. It’s a small word with a big role: it tells your function what value to send back to the place where it was called. Without it, your functions would work hard but never hand over their results!


In simple words, the javascript return keyword acts like a messenger. It carries the output of your function and delivers it to whoever asked for it. Whether you’re adding two numbers, creating a greeting, or fetching data — return is what makes those results usable outside the function.


In this guide, we’ll break down what is return keyword in javascript function, why it matters, and how to use it properly. You’ll also see plenty of clear, beginner-friendly javascript function return examples to lock in your understanding.


By the end of this article, you’ll know exactly how to make your functions speak back — and avoid the common mistakes that trip up beginners.


Let’s dive right in!

 



What Is the return Statement in JavaScript?


Imagine you ask your friend a question — like "What’s 2 + 2?" Your friend thinks for a second and then says, “It’s 4.”
That moment when your friend tells you the answer?
That’s what the return statement does in JavaScript.


When you call a function, it works behind the scenes to figure something out.
The return keyword is how that function gives you the answer back.
If the function doesn’t return anything, it’s like your friend just smiled but didn’t say the answer — not very helpful, right?


In short:
The return statement sends a result from a function back to you so you can use it.


Syntax

Here’s how you write a function that uses return:


function myFunc() { return value; }


  • function myFunc() → This creates a function called myFunc.
  • return value; → This sends value back when you run the function.

Example:


function addTwoNumbers() { return 2 + 3; } let result = addTwoNumbers(); console.log(result); // Output: 5


In this example:


 The function adds 2 + 3
 The return sends back 5
 We store the result in a variable and print it




Why Do We Use the return Statement?

The return statement is an essential part of JavaScript functions. It does two important jobs that make your code more efficient, clear, and functional. Let’s explore why you really need it:


1) To Send Back Values from a Function

The most common and primary reason we use the return statement is to send a result back from a function to where it was called.
When you use return, you're saying:

“Hey, I’ve calculated this value or result, and here it is for you to use!”

Without return, your function might do the work, but you won’t get any results back. It’s like asking someone to cook a meal, but they don’t serve it to you afterward. 

Example:


function add(a, b) { return a + b; // Sending the sum back } let sum = add(3, 4); console.log(sum); // Output: 7


In this example:

  • The function adds the numbers together, but it returns the result (7).
  • We can use the result later in our code by storing it in a variable (sum), which we then print.



 2. To Stop Function Execution Early

Another powerful use of return is to stop a function's execution as soon as you've gotten what you need.
When JavaScript encounters a return, it immediately exits the function, ignoring any code that comes after it. This is very helpful when you don’t need the function to continue once it’s completed its task.

Example:


function findPositiveNumber(num) { if (num <= 0) { return "Not a positive number"; // Stops here if the number isn't positive } return "It's a positive number"; // This runs only if the number is positive }


In this case:

  • If the number is not positive, return ends the function early with a message and skips the second return.
  • This prevents unnecessary checks and makes the code more efficient.

It’s like when you're reading a book, and you already know the ending — you skip ahead!




Can a JavaScript Function Return Multiple Values?


Short Answer:
No, a JavaScript function can only return one value directly.

But, don’t worry! We can work around this limitation. By using arrays or objects, we can group multiple values and return them all together. It’s like packing several items into one box and handing it over as a single return value.


Why Can’t a Function Return Multiple Values Directly?

JavaScript functions are designed to return a single value. If you try to return multiple values directly, JavaScript won’t know how to handle it — and it will give you an error. It's like trying to send more than one letter in an envelope that only fits one. 


Using Arrays to Return Multiple Values

A common workaround is to use arrays. You can pack several values inside an array and return that array. Later, you can access each item in the array by its index.

Example with Array:


function getInfo() { let name = "John"; let age = 30; return [name, age]; // Returning an array with two values } let info = getInfo(); console.log(info); // Output: ["John", 30] console.log(info[0]); // Output: John console.log(info[1]); // Output: 30


Here:

  • The function returns an array containing name and age as separate values.
  • Later, we can access each value by referring to the array index.

Using Objects to Return Multiple Values

Another powerful option is using an object. Objects allow you to store multiple values under different keys (properties), making it easier to refer to each value by name rather than by an index.

Example with Object:


function getUserInfo() { let name = "Alice"; let age = 25; return { name: name, age: age }; // Returning an object with named properties } let userInfo = getUserInfo(); console.log(userInfo); // Output: { name: "Alice", age: 25 } console.log(userInfo.name); // Output: Alice console.log(userInfo.age); // Output: 25


In this case:

  • The function returns an object with properties (name and age).
  • We access each property using the property name.



Key Things to Remember About return

The return statement is more than just a way to send values back from a function. There are a few important behaviors that come with using return. Let’s break them down clearly so you always know how to use it effectively.


 1. Code After return Won’t Run

One of the most important things to remember is that once JavaScript hits the return statement, it stops executing the function. This means any code after the return will not run.

It’s like telling someone to leave a room once you’ve given them what they need — once they leave, they won’t hear anything else! 🚪👋

Example:

function checkNumber(num) { if (num < 0) { return "Negative number"; // Stops the function here } console.log("This will never run!"); return "Positive number"; // This code will never be executed } console.log(checkNumber(-5)); // Output: Negative number


In this example:

  • When num < 0, the function returns and stops immediately.
  • The console.log statement after the return never runs.

So, remember: return acts like a “stop” button. It ends the function execution right there!


2. You Can Return Any Data Type

JavaScript is super flexible, and so is the return statement. You can return any data type, and even mix and match them. Whether it's a simple value or something more complex, you can send it back from a function.

Here are some types of data you can return:

  •  Numbers
  •  Strings
  •  Booleans
  •   Arrays
  •   Objects
  •  Functions
  •  Null
  •  Undefined
  •  Symbols
  •  BigInt

 



Frequently Asked Questions (FAQs)

In this section, we’ll answer some common questions related to the return statement in JavaScript. Whether you're just starting or looking for deeper insights, these answers will help clarify any doubts you might have!


 What Happens if There’s No return Statement?

If your function doesn’t include a return statement, it will still run the code inside the function, but it won’t return any value to where the function was called. By default, if a function doesn’t return anything, JavaScript returns undefined.

Example:


function greet(name) { console.log(`Hello, ${name}!`); } let result = greet("Alice"); console.log(result); // Output: undefined


Here:

  • The function greet doesn’t have a return statement.
  • Therefore, when we store the result in a variable, it’s undefined, as that’s the default return value for functions that don’t explicitly return anything.


Is return Required in Every Function?

No, return is not required in every function. You only need to use return if you want the function to return a value. Some functions are void functions, meaning they perform a task but don’t need to send any value back.

For example, a function that just prints something or modifies an external state might not need a return statement:

Example Without return:


function printMessage(message) { console.log(message); // This just does something but doesn't return any value } printMessage("Hello, world!"); // Output: Hello, world!


In this case:

  • The printMessage function does its job of logging the message, but it doesn’t return any value.
  • You don't need to use return unless you want to send a result back.


Can I Use return in Arrow Functions?

Yes, you can use the return statement in arrow functions. However, there are a few important differences to note:


Implicit return:   If your arrow function contains only one expression, you can omit the return keyword and let JavaScript implicitly return the result.

Example (Implicit Return):


const add = (a, b) => a + b; // No need for 'return' here console.log(add(2, 3)); // Output: 5


Explicit return: If you need to return something more complex (like an object or multi-line code), you'll need to use the explicit return statement.

Example (Explicit Return):


const getPerson = () => { return { name: "Alice", age: 25 }; // Explicit return is required for objects }; console.log(getPerson()); // Output: { name: "Alice", age: 25 }




Conclusion:

In this guide, we’ve covered the fundamentals of the return statement in JavaScript, from its purpose to how it works with different data types. The return statement is an essential concept in JavaScript, and understanding it will greatly improve how you structure and use functions in your code.


If you're new to functions in JavaScript, be sure to check out my What Are Functions in JavaScript? article for a deeper dive into the topic.


Try It Yourself!

Now that you understand how return works, give it a try! Write your own functions, experiment with different return values, and see how you can control the flow of your code using return.

Still Confused?

If you have any questions or find yourself stuck, feel free to drop your questions below! I’ll be happy to help you out.

 

Tags

Post a Comment

0 Comments
Post a Comment (0)
To Top