Lesson 12 of 15

If/Else Expressions

Control Flow with If/Else

Let's add conditional logic. In our language, if/else is an expression — it returns a value:

if condition then trueExpr else falseExpr

For example: if 1 then 42 else 0 evaluates to 42 (any non-zero number is truthy).

Comparison Operators

We need comparison operators to make conditions useful:

TokenMeaning
> (GT)Greater than
< (LT)Less than

New AST Node

{
    type: "IfExpr",
    condition: <expr>,
    thenBranch: <expr>,
    elseBranch: <expr>
}

Parsing If

if (this.peek().value === "if") {
    this.advance(); // consume 'if'
    const condition = this.parseExpr();
    this.advance(); // consume 'then'
    const thenBranch = this.parseExpr();
    this.advance(); // consume 'else'
    const elseBranch = this.parseExpr();
    return { type: "IfExpr", condition, thenBranch, elseBranch };
}

Evaluating If

A condition is truthy if it's not 0:

if (node.type === "IfExpr") {
    const cond = evaluate(node.condition, env);
    return cond !== 0
        ? evaluate(node.thenBranch, env)
        : evaluate(node.elseBranch, env);
}

Your Task

Add if/then/else expressions and comparison operators > and < to the interpreter.

Node.js loading...
Loading...
Click "Run" to execute your code.