This site uses tracking technologies. You may opt in or opt out of the use of these technologies.

Back to Javascript

Functions Return values

In JavaScript, functions can return values to the code that calls them, which allows you to use the result of the function in other parts of your code.

1. Basic Return

The return statement ends a function's execution and specifies a value to be returned to the function caller.

1function add(a, b) {
2 return a + b;
3}
4
5const sum = add(3, 5); // sum is now 8
6console.log(sum); // Outputs: 8
7

In this example, the add function returns the sum of a and b, which is then stored in the sum variable.

2. Returning Different Data Types

A function can return any type of data: numbers, strings, objects, arrays, or even other functions.

1function greet(name) {
2 return "Hello, " + name;
3}
4
5console.log(greet("Amir")); // Outputs: Hello, Amir
6

3. Early Return

You can use the return statement to exit a function early, which can be useful for validation or error handling.

1function divide(a, b) {
2 if (b === 0) {
3 return "Cannot divide by zero";
4 }
5 return a / b;
6}
7
8console.log(divide(10, 2)); // Outputs: 5
9console.log(divide(10, 0)); // Outputs: Cannot divide by zero
10

4. Returning an Object

When returning multiple values, you can use an object to group them.

1function getUserInfo() {
2 return {
3 name: "Amir",
4 age: 30
5 };
6}
7
8const userInfo = getUserInfo();
9console.log(userInfo.name); // Outputs: Amir
10

5. No Return Value (undefined)

If a function doesn’t explicitly return a value, it will return undefined by default.

1function logMessage() {
2 console.log("This is a message");
3}
4
5const result = logMessage(); // result is undefined
6console.log(result); // Outputs: undefined
7

6. Returning a Function

JavaScript supports higher-order functions, meaning a function can return another function.

1function createMultiplier(multiplier) {
2 return function (value) {
3 return value * multiplier;
4 };
5}
6
7const double = createMultiplier(2);
8console.log(double(5)); // Outputs: 10
9

By understanding how to use return values, you can build more modular, reusable, and maintainable code in JavaScript.