0

I have the following function:

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

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

What does the above return statement mean please?

Chris
  • 15,555
  • 3
  • 49
  • 58
balteo
  • 20,469
  • 52
  • 196
  • 362

1 Answers1

12

The && and || operators do not return boolean values in JavaScript.

a = b && c;

is essentially equivalent to:

a = !b ? b : c;

while

a = b || c;

is essentially equivalent to:

a = b ? b : c;

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

For the || operator it can be used to help extend namespaces that may or may not exist:

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

The && operator is often used for safe console logging:

//don't call console.log if there's no console
window.console && console.log('something');
zzzzBov
  • 157,699
  • 47
  • 307
  • 349