4

I would like to know if leaving an empty if statement for certain situations as:

else if(typeof console === 'undefined'){}

Just to have the code bypass the rest of the function It is an accepted and safe way to work or there are other recommendation practices for these cases?. Thank you.

Santiago Rebella
  • 2,362
  • 2
  • 20
  • 29

5 Answers5

5

From what information you've provided me, I can glean that the answer is "no". It will work, but it's bad style. If you would like to bypass the rest of the function, why not return; or put most of the logic in the if statement that pertains to it so that there is no bypassing at all?

Vinay
  • 5,876
  • 5
  • 37
  • 54
4

It's fine and safe to leave if branches empty, the only thing I would add is a comment:

else if(typeof console === 'undefined')
{
    //explanation why nothing has to go here
}

Without seeing the rest of the code I'm unsure how you're using this to "bypass the rest of the function", there may be a better way to do this.

martinwnet
  • 541
  • 2
  • 4
  • 10
1

Just don't write a block for a case you don't want to handle.

If you only want to do something when console exists, then do that:

if(typeof console !== 'undefined'){
    // your code
}
// else if(typeof console === 'undefined'){}
// you don't need that second part

Or maybe I didn't quite get your issue?

aaaaaa
  • 2,548
  • 3
  • 23
  • 31
1

Same as Pioul's answer, but I'd add that imo checking existence in javascript looks much tidier with the !! (notnot) operator.

if(!!console){
    // your code
}
// else if(!console){}
// you don't need that second part
Rob Hardy
  • 1,794
  • 14
  • 15
  • 1
    I ve been recommended to use allways === to avoid truthy cases. Also in a google talks video about javascript the good parts recommends this – Santiago Rebella Oct 10 '12 at 10:04
0

Sometimes it is useful to have debugging information printed out:-

if(typeof console !== 'undefined'){
    console.log("debug info");
}

Then, before releasing the code, simply comment out all the console.log's

//        console.log("debug info");

This can be done with a macro.

It will leave an empty if statement. But this is not a compilation error so that's OK.

Note, that if you're going to comment out the line it is important that braces are used. Otherwise you'd have the next line dependent on the if statement which would be a bleeding shame.

Quentin 2
  • 1,736
  • 1
  • 9
  • 7