M
Michael Wojcik
Prisoner said:heck, I'm still wondering why
variables can also be functions!
Why not?
Javascript (and other ECMAScript implementations) is a "functional"
programming language, which means that functions are first-class
entities: they can be created and manipulated in various ways while
the program runs. Other well-known functional languages are the LISP
family (LISP, Scheme), the ML family (Standard ML, OCaml), and Haskell.
But even non-functional languages usually offer support for variables
that refer to functions and can be used to evaluate functions. C has
function pointer types. COBOL has procedure-pointers. Most modern CPUs
have some variation on a von Neumann architecture, which treats code
as data. If a variable can hold a reference to data, why can't that
data be code? And it's not a far step from there to making code
directly manipulable.
(There are stranger things than that in programming, such as languages
that treat types as data and let you manipulate *those* dynamically.
Ultimately, in a von Neumann computer, it's all just data anyway.)
Treating code as data goes back to Goedel, Turing, and Church, all of
whom developed mathematics that could manipulate mathematical
expressions (Goedel-numbering, Turing machines, and lambda calculus).
They were inspired by Hilbert, who was curious about how far
mathematics could be formalized - specifically, if mathematics could
be extended to the point where you could algorithmically generate all
true mathematical statements.
As it turns out, you can't; but as Gregory Chaitin has pointed out,
this was one of the happiest failures ever in mathematics, since it
led more or less directly to modern information technology.
So: if you want to see formally why you can assign a function to a
variable, take a look at lambda calculus (various introductions to
Scheme are often good at explaining it) or Goedel-coding (Hofstadter's
_Goedel, Escher, Bach_ is a popular, if peripatetic, introduction) or
Turing machines. But it's really not such a stretch; and once you get
used to it, you'll find it can be quite a useful feature, since it
lets you express some solutions very elegantly.