Home

MakeCounter

MakeCounter is a factory function pattern used in programming education and practical code to create independent, stateful counter functions. A makeCounter function returns a new function (a closure) that, when invoked, yields the next value in a sequence. The internal counter variable is kept in the function's closure, making it private and inaccessible from the outside.

Implementation details vary: the counter may start at a specified initial value; each invocation increments the

Commonly used in examples about closures and higher-order functions, makeCounter demonstrates how functions can carry state

Notes: In JavaScript, makeCounter is a typical teaching example where a closure captures a count variable; in

value
and
returns
it,
or
may
return
the
value
before
increment
depending
on
convention.
Some
implementations
provide
additional
controls,
such
as
a
reset
method
or
a
way
to
set
the
current
value,
by
returning
an
object
with
such
methods
or
by
extending
the
returned
function
with
properties.
without
exposing
it.
In
languages
that
lack
closures
or
first-class
functions,
a
class
or
struct
with
a
counter
field
is
used
instead.
other
languages
the
same
concept
can
be
implemented
with
classes
or
modules.
Potential
downsides
include
memory
usage
from
closures
and
the
need
to
manage
state
carefully
to
avoid
unintended
sharing
between
instances.