views:

757

answers:

3

I'm used to using the if else shorthand:

var = (if statement) ? 'something' : 'something else';

Are there any other short hand methods available?

+1  A: 

Strictly speaking, that is not shorthand for an if/else statement. That's a ternary operator called a conditional operator.

Notice that while these do the same thing, they read differently:

// if the condition is true, we do something... maybe many things
if (condition) {
  var = 'something';
} else {
  var = 'something else';
}

// reads more clearly as an assignment based upon a condition
var = (condition) ? 'something' : 'something else';

In many cases it's fine to think of it as shorthand. Over time, your brain will instincitvely select a conditional operator where appropriate; but as you're just getting your feet wet you'll find the conditional operator to be a great way to express code more succinctly.

Larsenal
That "if statement" should be called "condition" for clarity.
Blindy
-1 You're really splitting hairs with your statement about strict equivalence and this could throw some developers off. If you clarify your statement, I'll remove my downvote.
Gavin Miller
+2  A: 

Not sure if this fits into what you're asking, but this also works:

var myVar:String = someStrThatMightBeNull || "default value if that other value is null";

So, if the first value to the right of the assignment operator is null/undefined, it will use the literal string.

inkedmn
I never knew that one
TandemAdam
Tehnomaag
+2  A: 
var myArray:Array = new Array();

Can be replaced with:

var myArray:Array = [];

Same goes for objects:

var myObj:Object = new Object();

Can be replaced with:

var myObj:Object = {};
grapefrukt