Monday, June 3, 2024
118
rated 0 times [  125] [ 7]  / answers: 1 / hits: 95041  / 13 Years ago, mon, january 16, 2012, 12:00:00

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?


More From » conditional-operator

 Answers
18
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

[#87989] Saturday, January 14, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradenc

Total Points: 75
Total Questions: 96
Total Answers: 129

Location: Burundi
Member since Thu, Feb 10, 2022
2 Years ago
;