Mr.Web
Mr.Web

Reputation: 7156

Javascript shortened if statement add else statement

I'm using a pre-compiled code and I have to put an else statement for the following if statement:

if(F && F[0]) for(var i=0; i<F.length; i++) readImage( F[i], '1417', '1417');

I usually work with this type of statement shortcut:

if(dog == 'billy') ? true : false ;

But can't figure out that first one.

Upvotes: 0

Views: 105

Answers (2)

musefan
musefan

Reputation: 48425

Mashing things into a single line often adds confussion. Your first block of code is this:

if(F && F[0]) 
    for(var i=0; i<F.length; i++) 
        readImage( F[i], '1417', '1417');

So all you need to do is add the else:

if(F && F[0]) 
    for(var i=0; i<F.length; i++) 
        readImage( F[i], '1417', '1417');
else
   //something

I personally find it a lot easier to use the brackets, it makes everything much more understandable:

if(F && F[0]) {
    for(var i=0; i<F.length; i++) {
        readImage( F[i], '1417', '1417');
    }
}
else {
   //something
}

In regards to your usual statement, you are confusing two different techniques, the standard if:

if(dog == 'billy') 
    //true 
else 
    //false

and the conditional operator (often called ternary), which does not require the if part, and is commonly use for conditional assignment:

var isTheDogCalledBilly = dog == 'billy' ? true : false;

Upvotes: 3

h2ooooooo
h2ooooooo

Reputation: 39540

You can place a single line of code in if/for/while etc. statements without using brackets. The following code would not execute bar(), but would execute rab():

var foo = false;
if (foo) 
    bar();
rab();

Indented your code would look like this:

if(F && F[0]) 
    for(var i=0; i<F.length; i++) 
        readImage( F[i], '1417', '1417');

Which is essentially the same as this:

if(F && F[0]) {
    for(var i=0; i<F.length; i++) {
        readImage( F[i], '1417', '1417');
    }
}

So you can just rewrite it to:

if(F && F[0]) {
    for(var i=0; i<F.length; i++) {
        readImage( F[i], '1417', '1417');
    }
} else {
    //Something else
}

Upvotes: 3

Related Questions