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:
- distinguish a value from a variable binding;
- declare mutable bindings with let;
- declare protected bindings with const;
- use simple and compound assignment;
- predict how nested scopes resolve names;
- explain block lifetime and shadowing;
- recognize duplicate, undefined, and constant-assignment errors; and
- choose names and mutability deliberately.
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.
| Situation | Recommended declaration |
|---|---|
| Policy threshold | const |
| Version label | const |
| Running total | let |
| Current status | let |
| Calculated value never reassigned | const 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.
| Environment | Bindings | Parent |
|---|---|---|
| Global | label = "outer" | None |
| If block | label = "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
| Pattern | Effect |
|---|---|
| status = "assigned" inside a block | Updates an existing outer binding when no local status exists. |
| let status = "assigned" inside a block | Creates a new local binding that hides the outer status. |
| const status = "assigned" inside a block | Creates 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:
| Statement | Before | After |
|---|---|---|
| let count = 1 | count undefined | count = 1 |
| count += 4 | count = 1 | count = 5 |
| count *= 2 | count = 5 | count = 10 |
This technique separates expression evaluation from mutation and makes incorrect expectations easier to locate.
2.20 Binding diagnostics
| Failure | Typical cause | Correction |
|---|---|---|
| Variable is already defined | A second declaration in the same scope | Assign to the existing let binding or rename the new declaration. |
| Undefined variable | Misspelling, use before declaration, or use outside lifetime | Correct the name, order, or scope. |
| Cannot assign to constant | Reassignment of a const binding | Keep the constant unchanged or redesign intentional state as let. |
| Invalid assignment target | The left side does not identify writable storage | Assign 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.
- Initialize mutable variables close to their first use.
- Give every update a clear reason.
- Avoid reusing one variable for unrelated meanings.
- Keep policy and configuration constants stable.
- Prefer calculated constants when a result does not need reassignment.
- Print or trace important transitions while learning and debugging.
2.22 Common mistakes
- Redeclaring instead of assigning: use assignment to update an existing let binding.
- Assigning before declaration: declarations must occur before use.
- Changing const to let reflexively: first decide whether mutation is genuinely required.
- Confusing assignment with equality: = writes; == compares.
- Assuming assignment creates a variable: it requires an existing target.
- Forgetting block lifetime: a local binding is unavailable after the block ends.
- Shadowing accidentally: a new local declaration can hide an outer name.
- Using compound assignment on an incompatible value: the underlying operation must make sense.
- Updating several related outputs inconsistently: keep state changes together when they represent one decision.
2.23 Guided practice
- Choose let or const for a tax rate, retry counter, customer name, and running balance.
- Rewrite let count = 1; let count = 2 to express an intentional update.
- Predict the final value after let x = 5, x += 3, and x *= 2.
- Explain why assignment inside a block may update an outer variable.
- Explain how adding let before the same assignment changes its meaning.
- Identify the error in assigning to an enclosing constant.
- Rename a shadowed variable to make both scopes explicit.
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:
- a duplicate declaration in one scope;
- an undefined read caused by a misspelling;
- assignment to the constant policy;
- use of note after its block has ended; and
- local shadowing of status without changing the outer status.
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
- List the active environments from current to outermost.
- Write the bindings owned by each environment.
- For a read, select the nearest matching name.
- For assignment, locate the nearest existing writable binding.
- Check whether that binding is constant.
- After leaving a block, remove its environment from the trace.
- Compare the predicted state with actual output.
2.26 Review questions
- What is the difference between a value and a binding?
- How does let differ from const?
- Why does assignment not create a new name?
- How is x += 2 related to reading and writing x?
- Why can the same name not be declared twice in one environment?
- In what order are nested environments searched?
- When does assignment update an outer binding?
- How does shadowing differ from reassignment?
- Why does a block-local name disappear after the block?
- Why should important policy constants generally not be shadowed?
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.