how to shorten jquery syntax if-else statement?

javascript, jquery, jquery-mobile

Solution

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.

Problem

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!

Original source