0

I know that it's called logical and but i mean specifically this way of using it, I was looking at some jsx packages and found this example

const Button = props => (
  <button className={'large' in props && 'large'}>
    {props.children}
    <style jsx>{`button{
      .large {padding: 50px;}
    `}</style>
  </button>
)

What does 'large' in props && 'large' mean? I know large is just a class so its irrelevant but can someone put into words what the operator is actually doing? Is it a short form of some kind of if statement and if so how would you type it out if it wasnt shortened? i hope this makes sense!!

edit: here's another example

 <p>{params.categoryName === "rent" ? "rent" : "sale"}</p>
      {loading ? (
        <h1>Loading</h1>
      ) : listings && listings.length > 0 ? (
        <>
          <ul>
            {listings.map((listing) => (
              <ListingItem listing={listing.data} id={listing.id} />
            ))}
          </ul>
        </>
      ) : (
        <p>No listings for {params.categoryName}</p>
      )}

3 Answers3

0

Is it clearer written as a ternary ?

props.includes("large") ? 'large' : '';

or a good old if/else ?

if(props.includes("large")){
     return "large";
} else {
     return "";
}

'large' in props is the same as props.includes("large"), it returns a boolean. If the boolean is true, then the next condition is evaluated with "and" (&&) . Since a string is truthy (if it has a length), it is returned as the result of the operation, that is, "large".

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
0

It is simply a quick way to say "if x is truthy, return y".

As MDN puts it: "if all values are truthy, the value of the last operand is returned." (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#description).

If it wasn't shortened it could look something like this:

x && y;

if(x) {
  return y;
} else {
  return false;
}
Mikkel-T
  • 1
  • 1
  • 2
0

&& is the logical AND operator in javascript. The logical AND operator && returns true if both operands are true, and returns false otherwise.

Example1:

className={'large' in props && 'large'}

In the first example, 'large' in props && 'large' is used as an Inline If with Logical && Operator which is equivalent to

if('large' in props && 'large'){
    return true;
}
else{
    return false;
}

Example2:

Similarly, in the second example

listings && listings.length > 0

which is equivalent to

if(listings && listings.length > 0) {
    // display list
}
else {
    // no list error message here
}

Hope, this will answer you question.

Farhan Ali
  • 116
  • 5