Chapter 13. Modules: breaking a program into pieces

 

This chapter covers

  • Importing code into JS Bin with script elements
  • Avoiding repeated variable names
  • Running functions without assigning them to variables
  • Using modules to organize your (shared) codebase

As the applications you develop become larger, involving more and more variables, objects, arrays, and functions, it can become harder and harder to work efficiently within a single program file. Good text editors and development environments can help, but even with their tools, it quickly becomes a good idea to split the code across multiple files.

For example, in The Crypt you have spacer, players, places, maps, and the game logic itself. You’ve probably noticed how long the code listings have become on JS Bin when all of the elements are included. Putting the code for each element in its own file can help you to focus on one piece of the program at a time and make it easier for different programmers to develop and test different parts of applications. Figure 13.1 shows your aim of splitting one large program into modules.

Figure 13.1. Breaking one large program into modules

13.1. Understanding bins and files on JS Bin

13.2. Importing files into other projects

13.3. Importing the Number Generator—further examples

13.4. Importing multiple files

13.5. Collisions—when imported code overwrites your variables

13.6. Immediately invoked function expressions (IIFE)

13.7. The Crypt—organizing code into modules

13.8. Summary