&& in a javascript function return expression that should not return a boolean

I have the following function:

function getLabelContent(element) {
    var label = element.find('label');
    return label[0] && label.html();
 }

I am puzzled by the return statement and especially the operator &&, which I thought was used to evaluate the operands of a boolean expression.

What does the above return statement mean?

0
source share
1 answer

Operators &&and ||do not return boolean values ​​in JavaScript.

a = b && c;

essentially equivalent to:

a = !b ? b : c;

and

a = b || c;

essentially equivalent to:

a = b ? b : c;

The coalescing behavior of these operators is useful in some cases.

For an operator, ||it can be used to expand namespaces that may or may not exist:

//use window.foo if it exists, otherwise create it
window.foo = window.foo || {};

&& :

//don't call console.log if there no console
window.console && console.log('something');
+9

Source: https://habr.com/ru/post/1534295/


All Articles