let
Prevents ConfusionThe let
special form prevents confusion. let
creates a
name for a local variable that overshadows any use of the same
name outside the let
expression (in computer science jargon, we
call this binding the variable). This is like understanding
that in your host’s home, whenever he refers to “the house”, he
means his house, not yours. (The symbols used to name function
arguments are bound as local variables in exactly the same way.
See The defun
Macro.)
Another way to think about let
is that it defines a special
region in your code: within the body of the let
expression, the
variables you’ve named have their own local meaning. Outside of the
let
body, they have other meanings (or they may not be defined
at all). This means that inside the let
body, calling
setq
for a variable named by the let
expression will set
the value of the local variable of that name. However, outside
of the let
body (such as when calling a function that was
defined elsewhere), calling setq
for a variable named by the
let
expression will not affect that local
variable.9
let
can create more than one variable at once. Also,
let
gives each variable it creates an initial value, either a
value specified by you, or nil
. (In the jargon, this is
binding the variable to the value.) After let
has created
and bound the variables, it executes the code in the body of the
let
, and returns the value of the last expression in the body,
as the value of the whole let
expression. (“Execute” is a jargon
term that means to evaluate a list; it comes from the use of the word
meaning “to give practical effect to” (Oxford English
Dictionary). Since you evaluate an expression to perform an action,
“execute” has evolved as a synonym to “evaluate”.)
This describes the behavior of let
when
using a style called “lexical binding” (see How let
Binds Variables).