A value that's either true
or false
.
Boolean
values help to make decisions in code. They appear any time a logical condition is checked. For example, the condition "Is a mouse button being pressed?" must be either true
or false
:
// If the user presses the mouse, draw a circle at
// the mouse's location.
if (mouseIsPressed === true) {
circle(mouseX, mouseY, 20);
}
The if
statement checks whether mouseIsPressed is true
and draws a circle if it is. Boolean
expressions such as mouseIsPressed === true
evaluate to one of the two possible Boolean
values: true
or false
.
The ===
operator (EQUAL) checks whether two values are equal. If they are, the expression evaluates to true
. Otherwise, it evaluates to false
.
Note: There's also a ==
operator with two =
instead of three. Don't use it.
The mouseIsPressed system variable is always true
or false
, so the code snippet above could also be written as follows:
if (mouseIsPressed) {
circle(mouseX, mouseY, 20);
}
The !==
operator (NOT EQUAL) checks whether two values are not equal, as in the following example:
if (2 + 2 !== 4) {
text('War is peace.', 50, 50);
}
Starting from the left, the arithmetic expression 2 + 2
produces the value 4
. The Boolean
expression 4 !== 4
evaluates to false
because 4
is equal to itself. As a result, the if
statement's body is skipped.
Note: There's also a !=
operator with one =
instead of two. Don't use it.
The Boolean
operator &&
(AND) checks whether two expressions are both true
:
if (keyIsPressed === true && key === 'p') {
text('You pressed the "p" key!', 50, 50);
}
If the user is pressing a key AND that key is 'p'
, then a message will display.
The Boolean
operator ||
(OR) checks whether at least one of two expressions is true
:
if (keyIsPressed === true || mouseIsPressed === true) {
text('You did something!', 50, 50);
}
If the user presses a key, or presses a mouse button, or both, then a message will display.
The following truth table summarizes a few common scenarios with &&
and ||
:
true && true // true
true && false // false
false && false // false
true || true // true
true || false // true
false || false // false
The relational operators >
, << code="">,
>=
, and <=< code=""> also produce
Boolean
values:
2 > 1 // true
2 < 1 // false
2 >= 2 // true
2 <= 2="" true="" <="" code=""/>
See if for more information about if
statements and Number for more information about Number
s.
Ejemplos
Referencias Relacionadas
Array
Una lista que mantiene diferentes tipos de datos en orden Los arreglos son útiles para almacenar datos relacionados.
class
Una plantilla para crear objetos de un tipo en particular.
for
Una forma de repetir un bloque de código cuando se conoce el número de iteraciones.
function
Un grupo de declaraciones con nombre.