Language: EN

programacion-tipos-boolean

Boolean type

The boolean type, also known as the logical type, is a variable type that allows representing and manipulating 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 along with logical and comparison operators and in control flow structures of the program.

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

Examples of boolean type in different languages

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

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

bool isEven = true;

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

In JavaScript the type is called boolean, but as it is 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
}

In Python, we can also work with the boolean type. But to declare it, we do not 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

Good practices Tips

As is often the case when talking about variables, the most important advice is to give a meaningful and identifiable name to the variables.

For example, instead of things like

let flag = true
let condition = true

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

let isVisible = true
let hasChildren = true;
let isValid = true;

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

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