Courses / Computer Science I
Programming II

State, Mutation, and Side Effects

Computer Science I 228 words Free to read

State and Side Effects

State is the collection of values a program holds at a given moment. Mutation is changing that state by reassigning a variable, adding to a list, or updating a field.

A side effect is any observable change a function makes beyond returning a value, such as mutating an argument or writing a file. A function without side effects whose output depends only on its inputs is pure.

ConceptMeaningRisk
MutationModifying existing dataHard to track state
AliasingTwo names, same objectSurprise modifications
Pitfall: b = a for a list does not copy. Mutating b also changes a because they share references.
Two names into one box, then two boxes for two names

The Event-Driven World

An event-driven program inverts control: you register handlers or callbacks to run when events happen, and an event loop waits and calls them. The outside world decides the order.

Handlers communicate entirely through shared state. Because order is unpredictable, mutation bugs multiply.

ThreatConsequencePrevention
BlockingFreezes the event loopKeep handlers short
Re-entrancyState half-updatedProtect shared state
Pitfall: Assuming handlers run in causal order. No promise is made about which event fires first.

Practise this lesson

The explanation above is free to read. The graded practice for this lesson lives in the Tryals app.

12practice questions
2interactive scenes

Programming II