Booleans
Boolean Values
When writing code we often need a data type that can represent the truth value, answer the Yes/No questions. JavaScript, among many other programming languages, has a Boolean data type. A JavaScript Boolean represents one of two values: true
or false
.
Note:
true
andfalse
are in lower case. There are no quotation marks around them, since they are not strings.Do not use
true
orfalse
as variable names.
Boolean Expression
A Boolean expression is an expression that evaluates to a Boolean value.
Comparison Operators
The comparison operators are used in logical statements to compare two values. The result of the operation is a boolean value. Here are the common comparison operators:
==
equal to
!=
not equal
>
greater than<
less than>=
greater than or equal to<=
less than or equal to
Run the following examples and check the comparison results:
console.log(25 == 5*5) // true
console.log(25 != 25) // false
console.log(25 > 5**2) // false
console.log(25 >= 5**2) // true
console.log('hi' == 'Hi') // false (stings are case sensitive)
console.log('Cat' != 'Chicken') // true
p = 10
t = 1
console.log(p < t) // false
Logical Operators
Logical operators allow a program to make a decision based on multiple conditions. There are three logical operators in JavaScript: &&
(and), ||
(or), !
(not)
The Truth Tables
&&
(and): if both are true
, the result is true
Expression | Result |
---|---|
true && true |
true |
true && false |
false |
false && true |
false |
false && talse |
false |
||
(or): if either of the two Boolean values is true
, the result is true
.
Expression | Result |
---|---|
true || true |
true |
true || false |
true |
false || false |
true |
false || false |
false |
!
(not): operates on only one Boolean value (or expression), result is the opposite.
Expression | Result |
---|---|
! true |
false |
! false |
true |
Examples
console.log(false && true) // false
console.log(4 == 2*2 && 2 == 3) // false
console.log((5 < 10) || (10 >= 5*2)) // true
console.log('Cat' == 'Dog' && !(6==8 || 3==3)) // false
// false && !(false || true) --> false && false --> false