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
  • 17,119
  • 5
  • 57
  • 60
balteo
  • 23,602
  • 63
  • 219
  • 412

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
  • 174,988
  • 54
  • 320
  • 367