camoflage
camoflage

Reputation: 177

JavaScript 'continue' within if statement

Within a for loop I can use break or continue. For example:

for(var i=0;i<5;i++){
  if(i=3){
    continue;   //I know this is absurd to use continue here but it's only for example
  }
}

But, what if I want to use continue from within a function within a for loop.

For example:

for(var i=0;i<5;i++){
  theFunction(i);
} 

function theFunction(var x){
  if(x==3){
    continue;
  }
}

I know that this will throw an error. But, is there any way to make it work or do something similar?

Upvotes: 5

Views: 16290

Answers (2)

Emmanuel Mtali
Emmanuel Mtali

Reputation: 4963

My solution would be, if putting for loop inside the function is not a big deal

function theFunction(initial, limit, jump) {
    for (var i = initial; i < limit ; i++) {
        if (i == jump) {
            continue;
        } else {
            console.log(i)
        }
    }
}

Upvotes: 0

Martin Ad&#225;mek
Martin Ad&#225;mek

Reputation: 18389

Use return value of that function and call continue based on it:

for (var i = 0; i < 5; i++) {
    if (theFunction(i)) {
        continue;
    }
}

function theFunction(x){
    if (x == 3) {
        return true;
    }

    return false;
}

Btw in your code you have if(i=3){, be aware that you need to use == or ===, single equals sign is for assignment.

Upvotes: 11

Related Questions