Skip to content

State in JavaScript – What Is a JavaScript State?

A state is the data a stateful program is managing.

What Is a Stateful Program?

A stateful program is a program whose output depends on external states (events).

Whenever a program is stateful, it means that the program manages (mutates) one or more states.

For instance, consider this stateful program that outputs a user’s TV channel choice:

let oldChannel = 5;
let currentChannel = 11;
function changeTVChannelTo(newNumber) {
if (typeof newNumber === "number") {
oldChannel = currentChannel;
currentChannel = newNumber;
return `Channel changed from ${oldChannel} to ${currentChannel}`;
}
}
// Change the channel of the TV:
changeTVChannelTo(48);
// The invocation above will return: "Channel changed from 11 to 48"

Try Editing It

In the snippet above,

  • oldChannel and currentChannel variables are the memories used to store states.
  • The variables’ values are the states.
  • changeTVChannelTo() is the stateful program used to manage the states.

What Is a Stateless Program?

A stateless program is one whose output does not depend on any external event.

Whenever a program is stateless, it means that the program does not manage any state.

Therefore, each data you input into a stateless function is processed independently of preceding inputs—because the program has no record of previous data inputs.

For instance, consider this stateless program that outputs a user’s TV channel choice:

function changeTVChannelFromTo(oldChannel, newChannel) {
if (typeof oldChannel === "number" && typeof newChannel === "number") {
return `Channel changed from ${oldChannel} to ${newChannel}`;
}
}
// Change the channel of the TV:
changeTVChannelFromTo(11, 48);
// The invocation above will return: "Channel changed from 11 to 48"

Try Editing It

In the snippet above, changeTVChannelTo() is a stateless program—as it manages no event.

In other words, the function is independent of any external data.