Home javascript How do I use return in JavaScript?

How do I use return in JavaScript?




Tell me about the return function as a kid, I can’t figure out how to use it in JavaScript.

Answer 1, authority 100%

  1. This is not a function, but a language construct.
  2. A function in JS must return something. Even without return , undefined will be returned.
    And if you need to return something meaningful, then using this operator you can implement it by telling the interpreter what to return.


// Perform calculations without returb
function withoutReturn (a, b) {
 // There is a result, but since this is an internal variable and it is not returned, the result dies with it
 // You can set it to an external variable, but this is fu, you don't have to be, keep the functions clean
 let c = a + b;
 // This could be here, although this is a procedure, not a function
 document.querySelector ('# test'). innerHTML = "Test";
function withReturn (a, b) {
 let c = a + b;
 // Here we did something and give the result, that is, the meaning as a function is present
 return c;
// undefined - waited for the addition, which happened, but did not return anything (i.e., the undefined marker was automatically returned)
console.info (withoutReturn (5, 5));
// 10 - added and returned, what is needed
console.info (withReturn (5, 5)); 
& lt; span id = 'test' & gt; & lt; / span & gt; 

Answer 2, authority 17%

The return statement has two purposes.

First, it is exit immediately from the function. Those. the operator transfers control to the code that called the current function.


function twice (a) {
 if (isNaN (a)) return; // Conditional exit without result (c undefined)
 return 2 * a; // Exit with the desired result
 a + = 5; // Code after calling return cannot be executed

Generally speaking, there are several ways to exit a function:

  • Reaching the last statement (the function code simply ends, similar to return; or return undefined; )
  • Direct call of the return
  • statement

  • Throwing an error, exception (throw 'something' , throw new Error )
    In this case, “stack unwrapping” is performed, we go down the call stack until we encounter an exception handler (construction try {} catch (e) {} )

Secondly, it is a return of a value , the so-called “function result”.


function max (a, b) {
 if (a & gt; b) return a; // Conditional exit with result a
 return b; // Unconditional exit with result b

PS : This actually applies to many programming languages, not just javascript.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions