0
0
Javascriptprogramming~5 mins

Return values in Javascript

Choose your learning style9 modes available
Introduction

Return values let a function give back a result after it finishes running. This helps you use that result later in your code.

When you want a function to calculate and give back a number, like adding two numbers.
When you need to get a value from a function to use somewhere else in your program.
When you want to check if something is true or false and use that answer later.
When you want to get a string or message from a function to show to the user.
When you want to stop a function early and send back a value immediately.
Syntax
Javascript
function functionName() {
  // do something
  return value;
}

The return keyword sends a value back to where the function was called.

Once return runs, the function stops running any more code inside it.

Examples
This function adds two numbers and returns the sum.
Javascript
function add(a, b) {
  return a + b;
}
This function returns a greeting string.
Javascript
function greet() {
  return "Hello!";
}
This function returns true if the number is even, otherwise false.
Javascript
function isEven(num) {
  return num % 2 === 0;
}
Sample Program

This program defines a function that multiplies two numbers and returns the product. Then it calls the function with 4 and 5, saves the result, and prints it.

Javascript
function multiply(x, y) {
  return x * y;
}

const result = multiply(4, 5);
console.log("The result is", result);
OutputSuccess
Important Notes

If a function does not have a return statement, it returns undefined by default.

You can return any type of value: numbers, strings, booleans, objects, or even other functions.

Summary

Use return to send a value back from a function.

After return, the function stops running.

Returned values let you use results from functions elsewhere in your code.