How exactly does return Javascript work

Wanted to know how it works exactly, where is it necessary to use within some scope like if etc.

 17
Author: filipelinhares, 2014-02-13

3 answers

As this documentation says, the return:

  • sets the value returned by a function. When there is no specified value, undefined will be returned.
  • stops the execution of the current function.

Return with value

function retornaValor() {
    return 1;
}
console.log(retornaValor());

The above code prints 1 to the console.

Return no value

function retornoVazio() {
    return;
}
console.log(retornoVazio());

The above code prints undefined to the console.

Return out of function (global)

On the other hand, if you try to use return outside of a function, in a code running in a browser, you will receive an error. For example, in Chrome, I got:

Uncaught SyntaxError: Illegal return statement

Block Return {}

Even if used within a block of Code, return will terminate the current function or cause the error as described above. There is no concept of returning a block. Example

function f(val) {
    if (val) {
        return 1;
    } else {
        return 2
    }
}

O code above will return 1 or 2 to the function, regardless of the keys.

How much and how to use return

Some people believe that each method / function should have a unique exit point. Consider the following example:

function f(a, cond) {
    if (cond) {
        return -2;
    } else {
        for (var i = 0; i < a.length; i++) {
            if (a[i] == 1) return i;
        }
    }
    return -1;
}

This function is small, but soon dozens of conditions and returns can arise, making the code difficult to understand.

An alternative would be as follows:

function f(a, cond) {
    val retorno = cond ? -2 : -1;
    if (!cond) {
        for (var i = 0; i < a.length; i++) {
            if (a[i] == 1) {
                retorno = i;
                break;
            }
        }
    }
    return retorno;
}

It's obviously a matter of personal opinion. Particularly, I believe that the problem lies in creating clear logic and not in the amount of returns.

See the examples in jsfiddle

 26
Author: utluiz, 2014-02-13 16:38:14

You can use return for 2 types of situations.

1. Return a value.
2. Stop the execution flow of the current function.



1. the usage situation is when you need to validate, calculate, or modulate the code.

function Calculadora(valor1, valor2, operacao) {
   var resultado = 0;

   if (operacao == "+")
       resultado = Soma(valor1, valor2);
   // ...   

   return resultado;
}

function Soma(valor1, valor2) {
   return parseInt(valor1) + parseInt(valor2);
}


2. the situation of use is when you no longer need to continue performing the current function, the result of it is already determined.

function ExibeValor(valor) // código apenas didático, sim é feio.
{
   if (parseInt(valor) <= 10) {
      alert('O valor é menor/igual a 10.');
      return;
   }

   if (parseInt(valor) > 10 && parseInt(valor) <= 20) {
      alert('O valor é maior que 10 e menor/igual a 20.');
      return;
   }

   if (parseInt(valor) > 20 && parseInt(valor) <= 30) {
      alert('O valor é maior que 20 e menor/igual a 30.');
      return;
   }

   if (parseInt(valor) > 30 && parseInt(valor) <= 40) {
      alert('O valor é maior que 30 e menor/igual a 40.');
      return;
   }
}

Let's assume you call the function passing the value 5, you will enter the 1 ° if and ready you do not need to run all other if to know the return of the function. This improves runtime and makes processing less costly.

 8
Author: Maicon Carraro, 2014-02-13 18:08:30

The return in javascript is similar to the return in Java and C#, which are the languages that I know, already in Delphi the return for the little I know works differently since when passing a return in javascript the function (or the current scope) is aborted by not continuing in the stream, and returning the value to its Invoker, this behavior can also be perceived using a debug in the browser such as the FireBug , or the Google native Chrome

function TesteRetorno(param){
if(param > 50){
    return "Maior que 50";
}
if(param > 10){
    return "Maior que 10";
}
return "Menor que 10";
}
alert(TesteRetorno(2));

Example

 0
Author: Fernando Leal, 2014-02-13 16:12:49