Exactly how Javascript works

Asked

Viewed 31,700 times

17

I wanted to know how it works exactly, where it is necessary to use within some scope as if etc.

  • 2

    You can explain better what you nay understands in the return?

  • It was about the question of blocks as if, but it was clarified.

3 answers

26


As this one says documentation, the return:

  • Sets the value returned by a function. When there is no specified value, undefined will be returned.
  • Stop running the current function.

Return with value

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

The code above prints 1 on the console.

Worthless return

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

The code above prints undefined on the console.

Return out of function (overall)

On the other hand, if you try to use the return out of a function, in a code executed 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 code block, the 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
    }
}

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

How much and how to use the return

Some people believe that each method/function should have a single output 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 can arise dozens conditions and returns, making the code difficult to understand.

An alternative would be the following:

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;
}

Obviously it is a matter of personal opinion. Particularly, I believe that the problem lies in creating a clear logic and not in the amount of returns.

See examples in jsfiddle

  • 1

    I think it is worth mentioning that javascript is able to interrupt the postback, or Submit, of the page when it returns false.

  • 1

    @Edgarmunizberlinck The question is not about events.

  • Anyway it costs nothing to include this information in your answer, just to make it complete.

  • 2

    So, some people think that the function has to have only one exit point. Some think that a default behavior should be defined and ifs with Return are used as guard conditions (for exceptions in the code stream (not to be confused with Exceptions)). I agree with the second type of programmer. PS: else gives cancer, return is the way.

  • @Edgarmunizberlinck I even wrote about this, actually about event manipulation in general, but it was awkward because it doesn’t add anything to the return, only details about a specific functionality and a specific return value. I would have to begin to explain the context about manipulating events and Bubbling. One more thing: postback isn’t exactly a synonymous of Submit.

  • @utluiz Sure, I know. At no time did I mean that Postback == Submit. If I made myself understood so it was not my intention.

Show 1 more comment

8

You can use the 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 usage situation is when you no longer need to continue running 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 suppose you call the function by passing the value 5, you will enter the 1° if and ready you don’t need to run all other if to know the return of the function. This improves the execution time and makes the processing less expensive.

0

The Return in javascript is similar to the Return in Java and C#, which are the languages I know, already in Delphi the Return for the little I know works differently while going through a javascript Return to Function (or the current scope) is aborted by not going through the stream, and returning the value to its invocator, this behavior can also be perceived using a browser debug like the Firebug, or the native Google 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

  • 2

    Delphi does not have Return. It is Result := or function name_da_name := .

  • Yes, yes it is called Result, correct is that if it is programmer Dephi surely must be thinking about the scope of Delphi Result.

  • Has the exit, but without returning value. An equivalent to return Javascript in Delphi, would be: Result := <valor>; exit;

  • Wrong again, Exit can return value yes sir from versions like 2010. Exit(1) for example returns 1.

  • ok, okay, I just quoted Delphi in my reply because I’ve seen friends who confuse javascript’s Return because they’re familiar with Delphi’s Result, giving the Return and thinking that the code that comes after will be executed, which does not happen in the case of javascript.

Browser other questions tagged

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