Language: EN

programacion-tipos-boolean

Boolean type

The boolean type, also known as the logical type, is a type of variable that allows representing and manipulating two logical values: true and false.

For example, if we want to evaluate if 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 construction in programming that is used together with 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.

Use of the boolean type in different languages

In most programming languages, the boolean type is represented by reserved keywords, such as bool or boolean. Let’s see 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's even
}
else
{
    // do something if it's odd
}

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's even
} else {
    // do something if it's odd
}

In Python, we can also work with the boolean type. But to declare it, it is not necessary to indicate the variable type

is_even = True

if is_even:
    # do something if it's even
else:
    # do something if it's odd

Best practices and cleaning tips Tips

As almost always 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 like

let isVisible = true
let hasChildrens = true;
let isValid = true;

In general, most boolean names should start with ‘is…’ or ‘has…‘. Also, whenever possible, use variables that are evaluated in a positive form. For example,

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

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