PeaBox Lab › PeaLang › Learn › Chapter 2 › Lesson 2

Part I — Foundations · Chapter 2 · Lesson 2 of 5 · 9 min read

Lesson 2: Values, Variables, let, const, Assignment, and Scope

Lesson level: Foundation

Purpose: Understand how PeaLang stores values under names, controls reassignment, resolves names through nested environments, and reports binding errors.

Learning objectives

By the end of this lesson, you should be able to:

2.1 Values and bindings

A value is data such as 42, 12.5, "gold", true, null, a list, or a map. A binding associates an identifier with a value inside an environment.

let quantity = 3

Here, 3 is the value and quantity is the binding name. Reading quantity asks the current environment for the value associated with that name.

A variable is therefore not the value itself. It is a named place in the program’s environment that currently refers to a value.

2.2 Declaring with let

Use let when the binding may be reassigned:

let status = "new"
status = "assigned"

The first statement defines the name. The second statement updates the existing binding. Assignment does not create a new variable; the name must already be defined in the current environment or an enclosing environment.

A let binding can be initialized from any expression:

let subtotal = quantity * unit_price

The expression is evaluated first, and its resulting value is stored under subtotal.

2.3 Declaring with const

Use const when the binding must not be reassigned:

const tax_rate = 0.18
const policy_name = "Standard Support"

Trying to assign a new value to a constant raises an error:

tax_rate = 0.20

The runtime reports that it cannot assign to the constant. Const protects the binding. When a constant refers to a collection, later chapters will distinguish rebinding the name from mutating the collection object itself.

2.4 Choosing between let and const

Prefer const when reassignment is not part of the design. Use let when state is intentionally updated. This communicates expectations to readers and lets the runtime reject accidental changes.

SituationRecommended declaration
Policy thresholdconst
Version labelconst
Running totallet
Current statuslet
Calculated value never reassignedconst where practical

2.5 Simple assignment

The assignment operator evaluates its right-hand expression and writes the result to the target:

let count = 1
count = count + 1

On the second line, the old value of count is read first, one is added, and the result is assigned back. Afterward, count is 2.

2.6 Compound assignment

PeaLang recognizes +=, -=, *=, and /=. Each reads the current target value, applies the arithmetic operator, and writes the result back.

let total = 10
total += 5
total *= 2

The value progresses from 10 to 15 to 30.

Compound assignment is concise when the target is intentionally updated. Use it only when the update remains obvious; a named intermediate expression may be clearer for complex business logic.

2.7 Assignment targets

At the foundation level, the target is usually a variable name. PeaLang also supports writable collection targets such as indexed or member locations, covered later with lists and maps.

An arbitrary computed expression is not a writable target. For example, a sum such as a + b produces a value but does not name a storage location that can receive assignment.

2.8 Evaluation order

For ordinary assignment, the right-hand expression is evaluated before the target receives the new value. For compound assignment, the current target value and right-hand value are combined before the write.

let x = 4
x = x * 3

The right-hand x still reads 4, so the new value becomes 12.

2.9 Duplicate declarations

A name cannot be defined twice in the same environment:

let score = 10
let score = 20

The second declaration fails because score already exists in that scope. If the intention is to update the value, use assignment rather than another let declaration.

2.10 Undefined names

Reading or assigning a name that does not exist in the current or enclosing environments produces an undefined-variable error:

print subtotal
missing_value = 3

For undefined reads, the runtime may offer a close-name suggestion when a similar name exists. Treat this as a hint, then verify the intended identifier rather than accepting it blindly.

2.11 What scope means

A scope is the region of a program where a binding can be resolved. PeaLang uses nested environments. Each environment stores its own values and constants and may refer to a parent environment.

When a name is read, the runtime first checks the current environment. If it is absent, it searches the parent, then continues outward until the name is found or no environment remains.

2.12 Block scope

Control-flow blocks execute in nested environments:

let message = "outer"
if true {
    let local_note = "inside"
    print message
    print local_note
}

The block can read message from its parent environment and local_note from its own environment. After the block ends, local_note is no longer available outside it.

2.13 Assignment searches outward

If assignment does not find the target in the current environment, it searches parent environments:

let status = "new"
if true {
    status = "assigned"
}
print status

The block contains no local declaration named status, so assignment updates the outer binding. The output is assigned.

2.14 Shadowing

A nested environment may declare a new binding with the same name as one in a parent environment:

let label = "outer"
if true {
    let label = "inner"
    print label
}
print label

The inner print resolves the nearest binding and outputs inner. After the block ends, the outer print outputs outer.

Shadowing is valid but can confuse readers. Use it only when the relationship is clear; distinct names are often safer in business rules.

2.15 Constants across scopes

Assignment searches outward, but it cannot bypass const protection. If an enclosing environment defines a constant, a nested block cannot reassign it unless the block deliberately declares a separate local binding with the same name.

Prefer not to shadow important policy constants. A local binding that hides an outer constant can make code appear to use the shared policy while actually using a different value.

2.16 Trace environments explicitly

For nested code, track each environment separately rather than keeping one undifferentiated list of names.

EnvironmentBindingsParent
Globallabel = "outer"None
If blocklabel = "inner"Global

A read inside the block checks the block environment first. A read after the block uses the global environment because the block environment no longer exists.

2.17 Scope lifetime

A binding remains available while its environment remains active. Top-level bindings remain available throughout program execution. A block-local binding is created when the block runs and becomes inaccessible when the block ends.

Each loop iteration and function call can also create nested environments. Their detailed behavior is covered in the control-flow and functions chapters, but the same lookup principle applies: nearest scope first, then outward.

2.18 Reassignment versus shadowing

PatternEffect
status = "assigned" inside a blockUpdates an existing outer binding when no local status exists.
let status = "assigned" inside a blockCreates a new local binding that hides the outer status.
const status = "assigned" inside a blockCreates a protected local binding that hides the outer status.

The presence or absence of let or const changes the meaning substantially. A declaration creates a binding in the current environment; assignment searches for an existing binding.

2.19 State transitions

When a variable changes, describe the transition explicitly:

StatementBeforeAfter
let count = 1count undefinedcount = 1
count += 4count = 1count = 5
count *= 2count = 5count = 10

This technique separates expression evaluation from mutation and makes incorrect expectations easier to locate.

2.20 Binding diagnostics

FailureTypical causeCorrection
Variable is already definedA second declaration in the same scopeAssign to the existing let binding or rename the new declaration.
Undefined variableMisspelling, use before declaration, or use outside lifetimeCorrect the name, order, or scope.
Cannot assign to constantReassignment of a const bindingKeep the constant unchanged or redesign intentional state as let.
Invalid assignment targetThe left side does not identify writable storageAssign to a variable or supported collection location.

Fix the root cause rather than weakening declarations. Changing every const to let merely to silence an error removes useful protection.

2.21 Mutability as a design decision

Mutable state is necessary for counters, accumulators, workflow status, and iterative calculations. It also increases the number of states a reader must consider. Use the smallest amount of mutation that expresses the problem clearly.

2.22 Common mistakes

2.23 Guided practice

2.24 Hands-on lab: Trace a scoped workflow

Create scope_workflow.pea with this valid program:

const policy = "Support-v1"
let status = "new"
let attempts = 0
if true {
    let note = "processing"
    attempts += 1
    status = "assigned"
    print "Inside: {policy}, {status}, {attempts}, {note}"
}
print "Outside: {policy}, {status}, {attempts}"

Before running it, prepare an environment trace showing the global and block bindings after every statement. Then format, check, and run it.

Make separate temporary variants that demonstrate:

Deliverable: The valid source and output, an environment trace, and a diagnostic table containing each variant, expected failure or behavior, actual result, and correction.

2.25 Scope-debugging workflow

2.26 Review questions

2.27 Applied challenge

Refactor the Chapter 1 case-priority program to minimize mutation. Keep policy values as constants, identify calculated values that never need reassignment, and retain let only for outputs that genuinely change across branches. Then add a nested block that produces a local audit label without leaking that label or shadowing policy names.

Lesson summary

PeaLang environments associate names with values. Let creates a mutable binding; const creates a binding that rejects reassignment. Assignment updates an existing target, and compound assignment combines a read, an operation, and a write. Nested scopes resolve the nearest name first, can read or update enclosing bindings, and discard local bindings when they end. Clear mutability choices and explicit environment tracing prevent many state and scope defects.

Lesson status: Approved.

← Previous Next →