Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript *and* operator used for a string parameter [duplicate]

Tags:

javascript

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?

like image 840
BruceHill Avatar asked May 02 '26 17:05

BruceHill


2 Answers

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 );
};
like image 90
HenningCash Avatar answered May 05 '26 19:05

HenningCash


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
like image 36
Bergi Avatar answered May 05 '26 19:05

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!