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);

arr_9[2] = "Third element of first level";
console.log(arr_9);

Properties and methods[edit | edit source]

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 set it to abc.join().

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

You can also set a 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"]

pop and shift[edit | edit source]

The pop method removes and returns the last element of an array. The shift method removes and returns the first element of an array. The length property of the array is changed by both the pop and shift methods.

(Note: The shift method also changes all the index numbers of the array. For example, arr[0] is removed, arr[1] becomes arr[0], arr[2] becomes arr[1], and so on.)

First, make an array.

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

Then use pop or shift.

alert(arr);          // "0,1,2,3"
alert(arr.pop());    // "3"
alert(arr);          // "0,1,2"
alert(arr.shift());  // "0"
alert(arr);          // "1,2"

push and unshift[edit | edit source]

The push and unshift methods reverse the effect of pop and shift. The push method adds an element to the end of an array and returns its new length. The unshift method does the same with the beginning of the array and — like shift — adjusts the indexes of the elements.

arr.unshift("0"); // "0,1,2"
arr.push("3");    // "0,1,2,3"

Exercises[edit | edit source]

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

Further reading[edit | edit source]