This is documentation for Mathematica 4, which was
based on an earlier version of the Wolfram Language.
Wolfram Research, Inc.

2.6.7 Blocks Compared with Modules

When you write a program in Mathematica, you should always try to set it up so that its parts are as independent as possible. In this way, the program will be easier for you to understand, maintain and add to.

One of the main ways to ensure that different parts of a program do not interfere is to give their variables only a certain "scope". Mathematica provides two basic mechanisms for limiting the scope of variables: modules and blocks.

In writing actual programs, modules are far more common than blocks. When scoping is needed in interactive calculations, however, blocks are often convenient.

Mathematica variable scoping mechanisms.

Most traditional computer languages use a so-called "lexical scoping" mechanism for variables, which is analogous to the module mechanism in Mathematica. Some symbolic computer languages such as LISP also allow "dynamic scoping", analogous to Mathematica blocks.

When lexical scoping is used, variables are treated as local to a particular section of the code in a program. In dynamic scoping, the values of variables are local to a part of the execution history of the program.

In compiled languages like C, there is a very clear distinction between "code" and "execution history". The symbolic nature of Mathematica makes this distinction slightly less clear, since "code" can in principle be built up dynamically during the execution of a program.

What Module[vars, body] does is to treat the form of the expression body at the time when the module is executed as the "code" of a Mathematica program. Then when any of the vars explicitly appears in this "code", it is considered to be local.

Block[vars, body] does not look at the form of the expression body. Instead, throughout the evaluation of body, the block uses local values for the vars.

This defines m in terms of i.

In[1]:= m = i^2

Out[1]=

The local value for i in the block is used throughout the evaluation of i + m.

In[2]:= Block[{i = a}, i + m]

Out[2]=

Here only the i that appears explicitly in i + m is treated as a local variable.

In[3]:= Module[{i = a}, i + m]

Out[3]=