• 0

[JavaScript] alternative if syntax?


Question

If I'm not mistaken, this...

myVar.filters? "ie" : typeof myVar.style.MozOpacity=="string"? "mozilla" : ""

...is an alternative to a normally written if() {} else {} statement.

What is the normally written one? And if possible could someone explain how the ": ?" syntax works for this example.

Thank you! :)

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

The basic sintax is

condition ? val_if_true : val_if_false

Translating the code you have is like:

if( myVar.filters ) {
   var = "ie";
} else {
   if( myVar.style.MozOpacity == "string" ) {
       var = "mozilla";
   } else {
      var = "";
   }
}

Link to comment
Share on other sites

  • 0
if( myVar.filters ) {
   var = "ie";
} else {
   if( myVar.style.MozOpacity == "string" ) {
       var = "mozilla";
   } else {
      var = "";
   }
}

585607389[/snapback]

can that be shorted (yes, only slightly) to...

if( myVar.filters ) {
   var = "ie";
} elseif( myVar.style.MozOpacity == "string" ) {
       var = "mozilla";
   } else {
      var = "";
   }
}

I thought I could skim some more code off, only got rid of about 3 chars :s

Link to comment
Share on other sites

  • 0

except that myVar.style.MozOpacity is unlikely to ever be "string" as you've left out the typeof:

BTW var is a reserved word. So you can't use it as a variable name.

var brow='';
if(myVar.filters){brow='ie';}
if(typeof myVar.style.MozOpacity=='string'){brow='mozilla';}

though if you're doing a browser detect between IE and Mozilla:

var brow='',d=document;
if(d.all){brow='ie';}
elseif(d.getElementById){brow='mozilla';}

this is because if such proprietary things as -moz-opacity become mainstream in CSS the typeof may fail as it won't necessarily be maintained as a property of style. Use W3C DOM standards and your code won't break somewhen down the line.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.