1

I know that when we use the "&&", the logic is like this:{ boolean && action } -> if the boolean is true then return the "action". In my code it happens like this: if the src property exists, then return the <Avatar />. My question is: why is it like this? src doesn't have any true or false value. Why it happens like this ?

function Sidebar({src}) {
    return (
        <div>
            {src && <Avatar src={src} />}
        </div>
    )
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Robert B
  • 67
  • 5
  • 2
    Does this answer your question? [What does '&&' operator indicate with { this.props.children && React.cloneElement(this.props.children, { foo:this.foo})](https://stackoverflow.com/questions/40682064/what-does-operator-indicate-with-this-props-children-react-cloneelemen) – Lionel Rowe Sep 28 '20 at 16:44
  • If your question is, `Although "src" isn't a boolean value, why is the "&&" operator working?` The answer is: it doesn't look for a boolean value, it checks whether the value is truthy or falsy. All [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) values are considered to be boolean false. and the [rest](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) of them are boolean true. – Darshan K N Sep 28 '20 at 17:02
  • Thanks a lot! I didn't know about this truthy or falsy concept. Now everything is more clear. – Robert B Sep 28 '20 at 17:07

3 Answers3

0

src doesn't have any true or false value

It has a value (even if that value is undefined or null) that is truthy or falsy even if that value isn't a Boolean.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

src can have undefined or null value. So to avoid this.

First we are checking if src contains valid data which is neither undefined nor null And if that condition is true then we are passing that source to Avatar as props.

keshav
  • 135
  • 4
0

Just operator of javascript && operator will return last one if others in ahead different flase (each others != flase)

//just operator of javascript // && operator will return last one if //others in ahead different flase (mean others != flase)

let object = {a:1};

console.log(object && 1);
console.log(object && 1 && object);
console.log(null && object);
Viet Dinh
  • 1,871
  • 1
  • 6
  • 18