Sikau

How computers work · Day 6 · about 35 min

Logic gates

AND, OR, NOT, XOR — and building every one of them from NAND alone.

Tiny decisions, billions of times

A logic gate takes bits in and gives a bit out: AND is 1 only when both inputs are 1; OR when either is; NOT flips. A CPU is billions of these, made from transistors. Play with them — and watch the truth table light up.

One gate to rule them all

Here's the surprise: NAND (NOT-AND) alone can build every other gate. Real chips lean on this — one well-made gate, copied billions of times.

function not(a) {
  return nand(a, a);
}

function and(a, b) {
  return not(nand(a, b));
}

function or(a, b) {
  return nand(not(a), not(b));
}

function xor(a, b) {
  const n = nand(a, b);
  return nand(nand(a, n), nand(b, n));
}

function nor(a, b) {
  return not(or(a, b));
}

The rest of this lesson

  • Gates as tiny functionsexplain
  • From transistors to gatesexplain
  • Trace itpredict
  • Which gate?match
  • Build from NANDwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 13 lessons of How computers work