Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

State and transactions

State is the data describing a program's current situation. Learn how object mutation differs from replacing state, and how to group changes without assuming automatic rollback.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

let state = initialState;
const nextState = transition(state);
state = nextState;

Program state is data that affects subsequent behavior, such as variable values and object properties. A state transition transforms the current state into the next state. state is not a keyword, and “state and transactions” names a design concept here, not special JavaScript syntax.

let allows reassignment of a variable. const prevents reassignment but does not freeze an object. Mutation changes an existing object and is visible through other references to it. Replacing state with a new object leaves the previous object unchanged only if you do not mutate it; shared nested objects still require care.

A transaction is intended to treat a group of changes as one unit: commit all of them or commit none. Ordinary JavaScript assignments provide no automatic rollback; throw does not undo earlier writes. In the example, transfer validates first, prepares a new object, and finally replaces state. This limited pattern operates on local numeric data and does not cover external side effects.

Jobs do not execute simultaneously within one agent, but that does not provide a general transaction guarantee. await can yield control, and called code can synchronously re-enter application logic. The state transition itself uses only ECMAScript features, including features introduced in ECMAScript 2015. To produce the displayed output, the example needs a host that provides console.log. The Console API is not part of ECMAScript: browsers provide it as a Web API, and Node.js provides its own implementation. The presence of Node 24 does not establish browser API support.

Examples

let state = { left: 10, right: 0 };

function transfer(amount) {
  if (!Number.isInteger(amount) || amount <= 0 || amount > state.left) {
    return false;
  }
  const nextState = {
    left: state.left - amount,
    right: state.right + amount
  };
  state = nextState;
  return true;
}

const before = state;
console.log(transfer(3));
console.log(JSON.stringify(state));
console.log(transfer(20));
console.log(JSON.stringify(state));
console.log(JSON.stringify(before));

Result

true
{"left":7,"right":3}
false
{"left":7,"right":3}
{"left":10,"right":0}

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources