Figuring Out How Many Items an Array Contains

In all modern JavaScript-enabled browsers, an array's length property contains the number of elements in an array. For example, the script in Figure 8-4 figures out how many images a web page holds.

How many images a web page contains

Figure 8-4. How many images a web page contains

Drop this JavaScript into the bottom of a web page with images, and you'll see how it works. The critical line is ❶, which tells JavaScript to create a variable called num_images and set it to the number of images in the built-in images array. If the page has 10 images, num_images will equal 10.

Get The Book of JavaScript, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.