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?

0

1 Answer 1

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');
Sign up to request clarification or add additional context in comments.

6 Comments

This is awesome to know
+1 for showing usage cases.
By the way b && c; is not exactly equivalent to !b ? b : c; when b is falsy but not false
@megawac - I don't think that's correct: "" && true returns ""
@EnjoysTurtles whoops you're correct misconception thanks
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.