programacion-tipos-boolean

Boolean type

  • 2 min

The boolean type, also known as the logical type, is a variable type that allows you to represent and manipulate two logical values: true true and false false.

For example, if we want to evaluate whether a number is even, we can use a boolean expression that returns true if the number is even and false if it is not.

The boolean type is a basic construct in programming that is used alongside logical and comparison operators and in program flow control structures.

The name “boolean” comes from the British mathematician and logician George Boole, who introduced Boolean logic in the 19th century.

Boolean Type Examples

In most programming languages, the boolean type is represented using reserved keywords, such as bool or boolean. Let’s look at some examples.

In C, C++, C#, and Java we can declare boolean variables using the keyword bool

bool isEven = true;

if (isEven)
{
    // do something if it is even
}
else
{
    // do something if it is odd
}
Copied!

In JavaScript the type is called boolean, but being dynamically typed we only need to use let to declare the variable

let isEven = true;

if (isEven) {
    // do something if it is even
} else {
    // do something if it is odd
}
Copied!

In Python, we can also work with the boolean type. But to declare it, we don’t need to specify the variable type.

is_even = True

if is_even:
    # do something if it is even
else:
    # do something if it is odd
Copied!

Best Practices Tips

As almost always when talking about variables, the most important tip is to give variables a meaningful and identifiable name.

For example, instead of things like

let flag = true
let condition = true
Copied!

Use names that reflect the purpose of the variable, such as

let isVisible = true
let hasChildren = true;
let isValid = true;
Copied!

In general, most boolean names should start with ‘is…’ or ‘has…’. Also, whenever possible, use variables that evaluate positively. For example,

let isValid = true   // preferable
let isInvalid = false  // less preferable
Copied!

The reason is that it’s easier to understand that something isValid, than isInvalid, which implicitly carries a negation in the name (it might seem trivial, but in long codes, it improves readability).