In Ruby, I can write a || b
and the function will choose a if it exists, and if not, b.
How can I do this in JQuery without writing something grossly cumbersome like:
if (a){
a
} else {
b
}
Also, does JQuery have an equivalent to Ruby's a ||= b
?
In Ruby, I can write a || b
and the function will choose a if it exists, and if not, b.
How can I do this in JQuery without writing something grossly cumbersome like:
if (a){
a
} else {
b
}
Also, does JQuery have an equivalent to Ruby's a ||= b
?
-
2
a = a || b;
should work. Are you having issues? – hayesgm Commented Aug 17, 2011 at 4:52 - 1 jQuery doesn't have operators, JavaScript OTOH does. – mu is too short Commented Aug 17, 2011 at 5:04
3 Answers
Reset to default 8jQuery is just a JavaScript library and in JavaScript we have the same.
var c = a || b;
This is because
If the first object is truthy, that gets returned. Otherwise, the second object gets returned.
In JavaScript, a || b
evaluates to the first truthy value (or the last value if both are falsy), just as in Ruby. (Remember, jQuery is just a library for JavaScript.)
However, JavaScript has many more falsy (non-truthy values) than Ruby does so care may need to be taken. See Truthy and Falsy: When All is Not Equal in JavaScript.
For instance, in JavaScript: "" || "foo"
will result in "foo"
although it would have evaluated to ""
in Ruby.
Happy coding.
And yes, JavaScript supports x Q= y
for all binary operators x = x Q y
. An easy way to find out is to just Try It And See :)
var myVariable = myVariable || "Default";