Next: , Up: let

let Prevents Confusion

The 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. This is like understanding that whenever your host refers to `the house', he means his house, not yours. (Symbols used in argument lists work the same way. See The defun Special Form.)

Local variables created by a let expression retain their value only within the let expression itself (and within expressions called within the let expression); the local variables have no effect outside the let expression.

Another way to think about let is that it is like a setq that is temporary and local. The values set by let are automatically undone when the let is finished. The setting only affects expressions that are inside the bounds of the let expression. In computer science jargon, we would say “the binding of a symbol is visible only in functions called in the let form; in Emacs Lisp, scoping is dynamic, not lexical.”

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 called `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'.)