Skip to content
Advertisement

JavaScript shorthand ternary operator

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?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement