Logical Operators

Defination

Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

Syntax

1
a1 = true && true // t && t returns true
2
a2 = true && false // t && f returns false
3
a3 = false && true // f && t returns false
4
a4 = false && (3 == 4) // f && f returns false
5
a5 = 'Cat' && 'Dog' // t && t returns "Dog"
6
a6 = false && 'Cat' // f && t returns false
7
a7 = 'Cat' && false // t && f returns false
8
a8 = '' && false // returns ""
9
a9 = false && || // returns false
Copied!

Usage

1
function Mailbox(props) {
2
const unreadMessages = props.unreadMessages;
3
return (
4
<div>
5
<h1>Hello!</h1>
6
{unreadMessages.length > 0 &&
7
<h2>
8
You have {unreadMessages.length} unread messages.
9
</h2>
10
}
11
</div>
12
);
13
}
14
15
const messages = ['React', 'Re: React', 'Re:Re: React'];
16
ReactDOM.render(
17
<Mailbox unreadMessages={messages} />,
18
document.getElementById('root')
19
);
Copied!

References