Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to shorten jquery syntax if-else statement?

I'm using a lot of these:

$text = $menu.jqmData('menu-text') ? 
           $menu.jqmData('menu-text') : self.options.menuTxt;

It already is the "shorthand" syntax, but I'm wondering, whether it's possible to reduce the above line even further. There must be a better way than checking for $menu.jqmData('menu-text') and then writing the whole thing again. Isn't there?

Thanks for help!

like image 908
frequent Avatar asked Apr 13 '12 09:04

frequent


1 Answers

A shorter way is to use the double pipe. It basically uses the second value if the first is falsy.

$text = $menu.jqmData('menu-text') || self.options.menuTxt;

You can also use it multiple time in the same line. Let's say you had a variable uberMenuTxt which takes priority over the other two and you could do it like so.

$text = uberMenuTxt || $menu.jqmData('menu-text') || self.options.menuTxt;

It basically keeps on going every time the current value is falsy and will stop at the first that is not.

like image 200
GillesC Avatar answered Nov 06 '22 02:11

GillesC