How to Return a Value in JavaScript

Man in Front of a Computer

Seizo Terasaki / Digital Vision / Getty Images

The best way to pass information back to code that called a function in JavaScript is to write the function so the values that are used by the function are passed to it as parameters and the function returns whatever value it needs to without using or updating any global variables.

By limiting the way in which information is passed to and from functions, it is easier to reuse the same function from multiple places in the code.

JavaScript Return Statement

JavaScript provides for passing one value back to the code that called it after everything in the function that needs to run has finished running.

JavaScript passes a value from a function back to the code that called it by using the return statement. The value to be returned is specified in the return. That value can be a constant value, a variable, or a calculation where the result of the calculation is returned. For example:

return 3;
return xyz;
return true;
return x / y + 27;​You can include multiple return statements into your function each of which returns a different value. In addition to returning the specified value the return statement also acts as an instruction to exit from the function at that point. Any code that follows the return statement will not be run.
function num(x, y) {
if (x !== y) {return false;}
if (x < 5) {return 5;}
return x;
}

The above function shows how you control which return statement is run by using if statements.

The value that is returned from a call to a function is the value of that function call. For example, with that function, you can set a variable to the value that is returned using the following code (which would set result to 5).

var result = num(3,3);

The difference between functions and other variables is that the function has to be run in order to determine its value. When you need to access that value in multiple places in your code, it is more efficient to run the function once and assign the value returned to a variable. That variable is used in the rest of the calculations.

Format
mla apa chicago
Your Citation
Chapman, Stephen. "How to Return a Value in JavaScript." ThoughtCo, Aug. 26, 2020, thoughtco.com/javascript-functions-2037203. Chapman, Stephen. (2020, August 26). How to Return a Value in JavaScript. Retrieved from https://www.thoughtco.com/javascript-functions-2037203 Chapman, Stephen. "How to Return a Value in JavaScript." ThoughtCo. https://www.thoughtco.com/javascript-functions-2037203 (accessed March 19, 2024).