What are the ways to use Return in Javascript and how do they work?

Asked

Viewed 233 times

1

I guess as simple as it may seem, I didn’t quite understand the return javascript.

There are some doubts that I would like to understand better, and what would be the best situations to use them.

function soma(valor1,valor2){
    var resultado = 0;
    resultado = valor1 + valor2;
    return resultado;
}

'Cause when I wear return result the code works and in the second option not?

function soma(valor1,valor2){
    var resultado = 0;
    resultado = valor1 + valor2;
    return;
}
  • Because in the second option you do not return anything. The syntax is return [[expression]];. The definition of the declaration is: "The expression whose value will be returned. If omitted, Undefined is returned." fountain

  • I understood perfectly, so in this case it would not be convenient to use an empty Return at the end of the function, because it would not return any value to me, right?

  • The first is returning the result (returns result), the second is out of the method (returns only), you are saying that from now on you will do nothing, see that you put the return at the end of the method... ie, even if you put anything below the return, he will return nothing more.

  • @Ivanferrer Thank you, I understand.

2 answers

2

The statement return finalizes the execution of a function and specifies the values that must be returned to where the function was called. (MDN documentation)

By omitting in the return the variable resultado, created within the function, who called the function does not receive any value, just executed the function and finished in the return, that is not necessary at the end of the function, since the end of the function is where it ends.

The return (with nothing) is only useful in the middle of the function, when you want to finish it on that line.

For example:

function f(x){

   if(x != 1){
      return; // finaliza a função sem retornar nada
      // return x*10; // ou finaliza retornado alguma coisa
   }

   alert("alerta");

}

In the above case, if the condition x != 1 is met, the function ends and does not arrive even in the alert.

But the return is usually used to return a value created within the function, as in your first example.

  • Thanks, I was able to understand perfectly. When I put a value other than 1 when calling the function, an alert box is returned. Therefore when placing the value 1, Undefined is returned.

  • Yes, it was just an example. To return a value, as said, Return must be followed by the value you want to return, as in your first example.

1

The return is used to return something, if you do not set anything for it, it will only return an output of the method:

   function soma() {

    //retorna soma 3 mais 4 => 7
    return (3 + 4);

    } 

   function verdadeOuMetira(p1, p2) {
      //retorna true (caso a soma seja 7), ou false (caso a soma seja diferente de 7)
      return ((p1 + p2) == 7);
   } 

    function soma() {
    var soma = (3 + 4);
    //retornando um valor de uma variável, retorna soma 3 mais 4 => 7
    return soma;

    } 

    function soma(callback) {

    //retorna soma 3 mais 4 => 7
    return callback();

    } 

   // passando um método callback de soma para o método de cima
      soma(function(){
            return 3 + 4;
       })

To better understand, see the example below:

    function soma() {
    var soma = (3 + 4);
    return; //aqui você está saindo da função (pois você não definiu nenhum parâmetro para ser retornado...

    //o código foi retornado acima, então essa soma não será retornada
    return soma;

    } 

Using return;you are making a code output, to have an output value, you can use return false;, in this case you can test your method:

Example:

function checkValor(valor) {
  //aqui você está dizendo em qual caso ele vai retornar (verdadeiro ou falso)...
  if(valor.indexOf('texto') !== -1) {
    return true;
  }
  return false;
}
if (!checkValor('onnoon')) {
    console.log('sucesso, não existe mesmo!')
}
if (checkValor('onnoon')) {
    console.log('não é válido!')
}
if (checkValor('texto')) {
    console.log('É válido!')
}
  • Thanks, I was able to understand even more with your example. The only doubt I had was in relation to the passage "if(value.indexof('text') !== -1)". In this case, what would that be "!== -1" and not "=== -1" or "=== 1"

  • == (checks equality), === (checks if it is equal and if it is of the same type, example: bolean) the exclamation serves to deny ( ! ), (!param) is the same as (param == false).

  • .indexOf returns the position found in a text, when it does not find it is returned as -1, you can open another question about it or preferably do a search on Sopt about it.

  • I’ll take a look at that. I’m a beginner in javascript and I’m picking things up little by little, but all these tips I wrote down here in the notebook to give that "query" when I impale there in front. I really like to know how to understand each feature before moving on. Thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.