"Break" or "return false"?

4

Within a function there is a repetition structure, how much processing savings, which one is the best?

JavaScript

function minhaFuncao(boom){
    for(i = boom; i > 10; i--){
        if(i < 0){
            break;
        }
    }
}

or

function minhaFuncao(boom){
    for(i = boom; i > 10; i--){
        if(i < 0){
            return false;
        }
    }
}

Is there any other way even more economical?

    
asked by anonymous 10.07.2014 / 02:56

2 answers

2

There are 3 options that depend a little on what you want. Note that your code never goes into if because the condition inside for does not allow negative values. Your for runs for the last time when i is 1 and doing i-- gives you a last value of 0 and its if looks <0 . Having said that the options are:

break;

Break stops the loop and moves on to the first line of code after of the loop. If you do not need to go through all the iterations of a loop but need to run code after the loop, use this option.

continue;

The continue jumps to the next iteration of the loop. If you do not need to run all the code for a specific iteration, but need all iterations, use this option.

return;

The return stops the function it is in and returns the value after the word "return". It is inside a loop, switch or other the function stops immediately and does not execute the next line to return.

How much processing savings depends on what you need. The most economical is the return because it is the most powerful and ensures that no further code is run. The suggestion is to always use the most defenitive and do not limit the code you want to run.

Is it useful to use these methods to save processing? Yes, of course.

    
10.07.2014 / 09:22
2

The break in the case of for will serve to break the loop of for , thus being by the most ideal past function. If it has code, it will run normally, ie only the loop will be stopped. In this case it will not involve anything in processing, because the loop is interrupted.

return false to fully execute your code and consequently processing.

Example: Demo

function Imprimir(p) {
    var texto = ""
    var i;
    var demo = document.getElementById("demo");
    for (i = 1; i <= 10; i++) {        
        if (i == 6) {
            if (p === 1) 
            { 
                break; 
            } 
            else 
            { 
                return false;
            }
        }
        texto += "Numero: " + i + "<br>";
    }   
    demo.innerHTML += texto + "<br>";
}
Imprimir(1);
Imprimir(1);
Imprimir(2);

The first two will be printed, because break was used while the last one for the function execution or output.

    
10.07.2014 / 03:08