🎓 A1Learner
🔍
0 of 50 lessons completed

Solidity Boolean Logic

Boolean logic is a way to combine true and false values into one new true or false value. Solidity uses three small operators for this job.

AND gives true only when both sides are true

The && operator needs both inputs to be true. One false input makes the whole result false.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract AndGate {
    function bothTrue(bool a, bool b) public returns (bool) {
        return a && b;
    }
}

OR gives true when at least one side is true

The || operator is more relaxed than &&. It gives false only when both inputs are false.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract OrGate {
    function eitherTrue(bool a, bool b) public returns (bool) {
        return a || b;
    }
}

AND can join a comparison with a bool

This check joins two facts with &&. The visitor must be old enough and must hold a ticket.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract EntryCheck {
    function canEnter(uint256 age, bool hasTicket) public returns (bool) {
        return age >= 18 && hasTicket;
    }
}

Example

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract EntryRules {
    function canEnter(uint256 age, bool hasTicket) public returns (bool) {
        return age >= 18 && hasTicket;
    }

    function hasAccess(bool hasTicket, bool hasPass) public returns (bool) {
        return hasTicket || hasPass;
    }

    function isLockedOut(bool hasTicket) public returns (bool) {
        return !hasTicket;
    }
}

Key points

  • AND: the && operator gives true only when both sides are true.
  • OR: the || operator gives true when at least one side is true.
  • NOT: the ! operator flips a value, so true becomes false and false becomes true.
  • Bool inputs: a function can take bool parameters, just like it takes number parameters.
  • Combined checks: one return line can join a comparison and a bool with && or ||.

In this example, one contract holds three entry rules. The canEnter function joins age >= 18 with hasTicket using &&, hasAccess joins a ticket and a pass using ||, and isLockedOut flips hasTicket using !.

Note

both sides of && and || must be bool values, because Solidity never guesses whether a number counts as true.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Remix IDE

Exercise

What does the expression true && false give?