JavaScript shorthand ternary operator

Web_Designer picture Web_Designer · Jan 16, 2012 · Viewed 57.8k times · Source

I know that in PHP 5.3 instead of using this redundant ternary operator syntax:

startingNum = startingNum ? startingNum : 1

...we can use a shorthand syntax for our ternary operators where applicable:

startingNum = startingNum ?: 1

And I know about the ternary operator in JavaScript:

startingNum = startingNum ? startingNum : 1

...but is there a shorthand?

Answer

Brad Christie picture Brad Christie · Jan 16, 2012
var startingNumber = startingNumber || 1;

Something like that what you're looking for, where it defaults if undefined?

var foo = bar || 1; // 1
var bar = 2;
foo = bar || 1;     // 2

By the way, this works for a lot of scenarios, including objects:

var foo = bar || {}; // secure an object is assigned when bar is absent