build-a-programming-language / lesson-23.md
Lesson 23 · Evaluation

The bang operator and truthiness

The prefix ! inverts a value's truth. Today you evaluate it, which forces the first decision about what counts as true or false in this language - its notion of truthiness.

The goal

Evaluate the prefix ! operator by defining which values are truthy.

Start here - the target
TO DO
Scenario: Evaluating the bang operator
Givena program using the prefix ! operator
Whenthe evaluator evaluates !true, !false, !5, and !!5
Thenthe results are false, true, false, and true respectively
Andthe rule your helper encodes is: false and null are the only non-truthy values, everything else (including 5) is truthy
Background

Evaluating ! forces you to answer a question every language must: which values are truthy? This language keeps it simple - false and null are falsy, and everything else, including 0 and empty strings, is truthy. The ! operator is where that rule first becomes visible.

So !true is false and !false is true. The interesting cases are !5false (because 5 is truthy) and !!5true (invert twice). Your helper should also treat null as non-truthy even though there is no null literal to write yet - if and while will produce null values and lean on the exact same definition to decide whether to take a branch or keep looping.

Make it work
func evalBang(right Object) Object {
switch right {
case TRUE: return FALSE
case FALSE: return TRUE
case NULL: return TRUE
default: return FALSE // any other value is truthy, so ! makes it false
}
}
CheckpointDONE
The bang operator inverts truthiness, and the language's truth rule is fixed. Commit.