JavaScript/Arrays

From Wikibooks, open books for an open world
Jump to navigation Jump to search




In JavaScript, an array is an object where you can store a set of values under a single variable name. So far, it's the same as in many other languages. But there are distinctions.

  • It's not necessary that the values are of the same data type. You can put everything you want in an array and worry about the data type later. (But there are also typed arrays where all values have the same data type.)
  • When you create an array, you do not need to declare a size - but you can. Arrays grow automatically. This makes arrays very convenient to use, but not well-suited for applications in numerical analysis.
  • Because arrays are objects, they have methods and properties you can invoke at will. For example, the .length property indicates how many elements are currently in the array. If you add more elements to the array, the value of the .length gets larger.
  • The element-counting starts at 0, which means, for instance, that the 5th element is located with [4].

(Hint: When using arrays, you should always use the bracket notation with non-negative integers, e.g., arr[3] = 42;. Technically, it's also possible to use the dot notation, but this leads - at least for beginners - to unexpected behavior.)

Create an array[edit | edit source]

First, as with all objects, there is a constructor.

"use strict";

const arr_1 = new Array(); // empty array
alert(arr_1.length);
const arr_2 = new Array(0, 2, 4); // 3 elements
alert(arr_2);

Next, the JavaScript syntax supports square brackets when creating or working with arrays.

"use strict";

const arr_1 = []; // empty array
alert(arr_1.length);
const arr_2 = [0, 2, 4]; // 3 elements
alert(arr_2);

You can predefine the size of an array when declaring it.

"use strict";

const arr_3 = new Array(50); // 50 elements
alert(arr_3.length);

Access an array element[edit | edit source]

Array elements are accessed for reading or writing with the usual bracket notation.

"use strict";

const arr_4 = [0, 2, 4, 6, 8];
alert(arr_4[3]);  // 6
arr_4[0] = 9;
alert(arr_4); // 9, 2, 4, 6, 8

When you access an element above the array's actual length, the size of the array will grow, and the new element will be created.

"use strict";

const arr_5 = [0, 2, 4, 6, 8];
arr_5[10] = 9;
alert(arr_5); // 0,2,4,6,8,,,,,,9
alert(arr_5.length); // 11

Varying data types[edit | edit source]

You can store values of different data types within an array.

"use strict";

const arr_6 = [0, "two", 4]; // number and string
console.log(arr_6);        // [0, "two", 4]

// and even values of data type 'array' can be stored
const arr_7 = [10, 11];
arr_7[2] = arr_6;          // array in array
console.log(arr_7);        // [10, 11, [0, "two", 4]]
console.log(arr_7.length); // 3

Nested arrays[edit | edit source]

As shown before, an array element may be an array (which itself may contain elements of type array (which itself may contain ...)). This can occur during runtime or during initialization. To access the lower levels directly, you must specify as many bracket pairs [] as necessary to reach this level.

"use strict";

const arr_8 = [ [0, 1], [10, 11, 12, 13], [20, 21] ];
console.log(arr_8[2]);    // one level goes to an array of numbers: [20, 21]
console.log(arr_8[1][1]); // two levels go to a number: 11

// same with assignments ...
arr_8[2][0] = "twenty";
console.log(arr_8[2]); // ["twenty", 21]

... and a little more complex

"use strict";

const arr_9 = []; // empty
arr_9[0] = [];
arr_9[0][0] = [];
arr_9[0][0][2] = "Hallo world!";
console.log(arr_9);  // [[[undefined, undefined, "Hallo world!"]]]

arr_9[2] = "Third element of first level";
console.log(arr_9);
// [[[undefined, undefined, "Hallo world!"]], undefined, "Third element of first level"]

Properties and methods[edit | edit source]

length[edit | edit source]

length is a property of each array (it's not a method). It represents the number of elements in that array.

alert([0, 1, 2].length);  // 3

Please notice that array indices are zero-based. Therefore the array's length is huger than the last index.

concat[edit | edit source]

The concat method returns the combination of two or more arrays. To use it, first, you need two or more arrays to combine.

const arr1 = ["a","b","c"];
const arr2 = ["d","e","f"];

Then, make a third array and set its value to arr1.concat(arr2).

const arr3 = arr1.concat(arr2); //arr3 now is: ["a","b","c","d","e","f"]

Note that in this example, the new arr3 array contains the contents of both the arr1 array and the arr2 array.

join and split[edit | edit source]

The join method returns a single string that contains all of the elements of an array — separated by a specified delimiter. If the delimiter is not specified, it is set to a comma.

There is also a split method that performs the opposite of join: it operates on a string, divides him into elements based on the specified delimiter, and returns an array that contains those elements. (Hint: split is a method of the data type string, not of array.)

To use join, first make an array.

const abc = ["a", "b", "c"];

Then, make a new variable and assign it to abc.join().

const a = abc.join();  // "a,b,c"

You can also use a dedicated delimiter.

// use 'semicolon' plus 'space' as delimiter
const b = abc.join("; ");  // "a; b; c"

Convert it back into an array with the string's split method.

const a2 = a.split(",");  // ["a", "b", "c"]
const b2 = b.split("; "); // ["a", "b", "c"]

push[edit | edit source]

The push method adds one or more elements to the end of an array and returns the array's new length.

"use strict";
const arr = [0, 1, 2, 3];

alert(arr);                // 0, 1, 2, 3
const len = arr.push(100);
alert(len);                // 5
alert(arr);                // 0, 1, 2, 3, 100

pop[edit | edit source]

The pop method removes the last element of an array and returns the element.

"use strict";
const arr = [0, 1, 2, 3];

alert(arr);                // 0, 1, 2, 3
const elem = arr.pop();
alert(elem);               // 3
alert(arr);                // 0, 1, 2

push and pop work at the end of an array; they reverse their respective effects.

unshift[edit | edit source]

The unshift method adds one or more new elements to the beginning of an array and returns the array's new length. It works by 'unshifting' every old element from its old index to , adds the new element to index , and adopts the array's length property. It is comparable with push but works at the beginning of the array.

"use strict";
const arr = [0, 1, 2, 3];

alert(arr);                // 0, 1, 2, 3
const len = arr.unshift(100);
alert(len);                // 5
alert(arr);                // 100, 0, 1, 2, 3

shift[edit | edit source]

The shift method removes the first element of an array and returns the removed element. It works by 'shifting' every old element from its old index to , adopts the array's length property, and returns the old first element. It is comparable with pop but works at the beginning of the array.

"use strict";
const arr = [0, 1, 2, 3];

alert(arr);                // 0, 1, 2, 3
const elem = arr.shift();
alert(elem);               // 0
alert(arr);                // 1, 2, 3

unshift and shift work at the beginning of an array; they reverse their respective effects.

Exercises[edit | edit source]

... are available on another page (click here).

See also[edit | edit source]