In jQuery Mobile I find the following code:
$.jqmData = function( elem, prop, value ){
return $.data( elem, prop && $.mobile.ns + prop, value );
};
What I do not understand is this construct:
prop && $.mobile.ns + prop
It is using Javascript's logical and operator, but for the key parameter for the jQuery data which is a string parameter. Can someone please explain this construct?
Javascript does not implicitly return Boolean values when using Boolean operators:
&& returns the second element, if both elements equal to true or the first, if one of them is false
|| returns the first element, if it equals to true, or the second, if the first matches false
Some examples:
("foo" && "bar") === "bar"
(1 && "foo") === "foo"
(undefined && false) === undefined
(1 || "foo") === 1
(0 || "foo") === "foo"
(undefined || "foo") === "foo"
(undefined || 1) === 1
(undefined || false) === false
Your case from jQuery mobile:
prop && $.mobile.ns + prop - in this case prop will be used if prop AND $.mobile.ns are equal to true. If one of them is false, $.mobile.ns will be used. I think in this situation it's used when prop === null which equals an empty string.
You could expand this to:
$.jqmData = function( elem, prop, value ){
if(prop == false)
prop = $.mobile.ns
return $.data( elem, prop + prop, value );
};
Can someone please explain this construct?
JavaScript's logical operators do not only work on booleans, but on any type. They will internally convert the values to boolean to check their truthiness, but they won't change the result type.
For strings, only the empty string is considered falsy. The AND operator && works like "if the left operand is falsy, return it, otherwise return the right operand". So if invoked on the string prop, it will check whether prop is the empty string and then return it, or otherwise concatenate it with $.mobile.ns. It's a shortcut for
!prop ? prop : $.mobile.ns+prop
// or, if restricted to strings:
prop == "" ? "" : $.mobile.ns+prop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With