Wednesday, February 24, 2016

Quick Tip: How to Create and Manipulate Arrays in JavaScript

This article was peer reviewed by Chris Perry and Marcello La Rocca. Thanks to all of SitePoint's peer reviewers for making SitePoint content the best it can be!

The length property of Array objects is one that many who are relatively new to JavaScript do not understand. Many mistakenly believe that the length tells you exactly how many entries there are in an array whereas this is only true of some arrays. Some beginners do not even realize that length is a writable property of arrays. To clarify just exactly how the length property works, let's take a look at what happens when we either change its value ourselves or run something that updates the array that also results in the length changing.

[author_more]

Let's start at the beginning. A JavaScript array has a property called length and optionally has numbered properties with names between 0 and 4294967294 inclusive. It also has a number of methods for manipulating the properties some of which we will look at as a part of our examination of how the length property works. Note that JavaScript does not support associative arrays and so while you can add named properties to an array, they do not form a part of the array and will be ignored by all the array methods. They also will not affect the length.

To make it easier to show exactly what happens to the array properties as we process various statements, we will run the following function after each piece of code. This will log the length of the array and all of the numbered properties to the browser's console.

var test = function(array) {
  console.log('length:'+ array.length);
  array.forEach(function(element, index, array) {
    console.log(index + ':' + element);
  });
};

Creating an Array

We will begin by looking at different ways to create an array in JavaScript. The first two of these examples create arrays where only the length is set and there are no numbered entries at all. The second two create numbered entries from 0 to one less than the length.

An array where the length is greater than the amount of numbered properties is known as a sparse array while one with the length equal to the number of numbered properties is a dense array.

//Creates an array with no numbered entries

var arr = new Array(5);
test(arr);
// length: 5

var arr = [];
arr.length = 5;
test(arr);
// length: 5

Note that the array literal notation (where you define a new array using just empty brackets) is preferred when creating new arrays.

var arr = ['a', 'b', 'c', 'd', 'e'];
test(arr);
// length:5, 0:a, 1:b, 2:c, 3:d, 4:e

var arr = [undefined, undefined, undefined, undefined, undefined];
test(arr);
// length:5, 0:undefined, 1:undefined, 2:undefined, 3:undefined, 4:undefined

The array methods that process the numbered properties (forEach in our case) will only process those that exist. If you instead process the array using a for or while loop then the loop will also attempt to process those properties that don't exist and the array will identify those entries that don't exist as being undefined. Your code would then be unable to distinguish between the last of the above examples and the first two. You should always use the array methods for processing an array where you are not certain that you are dealing with a dense array.

Changing the Length

The following examples look at what happens if we set a new length for the array that is less than the current length.

var arr = ['a', 'b', 'c', 'd', 'e', 'f'];
test(arr);
// length:6, 0:a, 1:b, 2:c, 3:d, 4:e, 5:f

var arr.length = 5;
test(arr);
// length:5, 0:a, 1:b, 2:c, 3:d, 4:e

var arr = ['a','b','c','d','e','f',,,];
test(arr);
// length:8, 0:a, 1:b, 2:c, 3:d, 4:e, 5:f

var arr.length = 7;
test(arr);
// length:7, 0:a, 1:b, 2:c, 3:d, 4:e, 5:f

Note that when creating an array using [] notation each entry consists of a value followed by a comma. Where the value is omitted then no property is created for that position. The last comma may only be omitted if there is a value supplied for that property as otherwise the length will be reduced by one.

Continue reading %Quick Tip: How to Create and Manipulate Arrays in JavaScript%


by Stephen Chapman via SitePoint

No comments:

Post a Comment