Lesson 10 of 15

Variables and Assignment

Adding Variables

A calculator is nice, but real languages have variables. We need:

  1. Assignment: let x = 10;
  2. Lookup: using x in an expression

The Environment

An environment is a mapping from variable names to values. We can use a plain JavaScript object:

const env = {};
env["x"] = 10;
console.log(env["x"]); // 10

New AST Nodes

We need two new node types:

  • LetStatement: { type: "LetStatement", name: "x", value: <expr> }
  • Identifier: { type: "Identifier", name: "x" }

Parsing let

When we see the let keyword, parse: let IDENT = expr ;

Evaluating Variables

if (node.type === "LetStatement") {
    env[node.name] = evaluate(node.value, env);
    return;
}
if (node.type === "Identifier") {
    return env[node.name];
}

Your Task

Build an interpreter that supports let declarations, variable references in expressions, and a print statement. Parse a program as a list of statements separated by semicolons.

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