O'Reilly logo

JavaScript® and AJAX for Dummies® by Andy Harris

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 5. Functions, Arrays, and Objects

In This Chapter

  • Making code manageable with functions

  • Passing parameters into functions

  • Returning values from functions

  • Examining functions and variable scope

  • Producing basic arrays

  • Retrieving data from arrays

  • Building a multi-dimensional array

  • Creating custom objects with properties and methods

  • Building object constructors

  • Building JSON data structures

It doesn't take long for your code to become complex. Soon enough, you'll find yourself wanting to write more sophisticated programs. When things get larger, you need new kinds of organizational structures to handle the added complexity.

You can bundle several lines of code into one container and give this new chunk of code a name. That's called a function. You can also take a whole bunch of variables, put them into a container, and give it a name. That's called an array.

This chapter shows you how to work with more code and more data — in the form of functions and arrays — without going crazy.

Breaking Code into Functions

It doesn't take long for code to get complicated. It would be good to have some sort of tool for managing the complexity and making code easier to handle. That's exactly what a concept called functions does for you.

Inviting ants to the picnic

To explain functions better, think back to an old campfire song. Figure 5-1 re-creates this classic song for you in JavaScript format. (You might want to roast a marshmallow while you view this program.)

Figure 5.1. Nothing reminds me of functions ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required