w3docs logo

JavaScript Arrays

In this chapter, we will explore JavaScript arrays.

In JavaScript, you can use arrays for storing multiple values in a single variable.

We can describe an array as a unique variable capable of holding more than one value simultaneously.

There exist two syntaxes for generating an empty array:

let arr = new Array();
let arr = [];

The second syntax is used most of the time. You can add initial elements in the brackets, like this:

w3docs logo Javascript arrays
let books = ["Html", "Css", "Javascript"]; console.log(books[0]); // Html console.log(books[1]); // Css console.log(books[2]); // Javascript

You can also replace an element as follows:

w3docs logo Javascript arrays
let books = ["Html", "Css", "Javascript"]; books[2] = 'Php'; // now ["Html", "Css", "Php"] console.log(books);

Either you can add a new one to the array, like this:

w3docs logo Javascript arrays add new element
let books = ["Html", "Css", "Javascript"]; books[3] = 'Php'; // now ["Html", "Css", "Javascript", "Php"] console.log(books); // Html, Css, Javascript, Php

The array length is the total count of the elements. Here is an example:

w3docs logo Javascript arrays length
let books = ["Html", "Css", "Javascript"]; console.log(books.length); // 3

In case you are going to show the overall array, you may use console.log, like this:

An array is capable of storing any types of elements:

w3docs logo Javascript arrays multitype
// mix of values let arr = ['Javascript', { sitename: 'W3Docs'}, true, function () { console.log('welcome'); }]; // get the object at index 1 and then show its name console.log(arr[1].sitename); // W3Docs // get the function at index 3 and run it arr[3](); // welcome

Arrays can be viewed as a special type of object. One of the most notable similarities is that arrays can end with a comma.

For instance:

let books = [
 "Html",
 "Css",
 "Javascript",
];

Methods

One of the most widespread uses of arrays is a queue. in computer science, it is known as an ordered assembly of elements that support the following two operations:

push - is used for appending an element to the end

shift - is used for getting an element from the beginning, advancing the queue. In consequence, the second element becomes the first.

Arrays support both of the above-mentioned operations, and it’s a widespread practice for developers.

You can use arrays for another practice as well. It’s data structure named stack, which supports two operations:

push - it’s aimed at adding an element to the end.

pop - is aimed at taking an element from the end.

In javascript, arrays work with as a queue and as a stack. With the help of arrays, you can add or remove elements to/from the beginning or the end.

Methods working with the end of an array

pop

This method is used for extracting and returning the last element of the array. For instance:

w3docs logo Javascript arrays pop element
let books = ["Html", "Css", "Javascript"]; console.log(books.pop()); // remove "Jasvascript" and alert it console.log(books); // Html, Css

push

You can use this method for appending the element to the end of the array, like this:

w3docs logo Javascript arrays push element
let books = ["Html", "Css"]; books.push("Javascript"); console.log(books); // Html, Css, Javascript

The calls books.push(...) and books[books.length] = ... are equal.

Methods working with the beginning of the array

shift

This method is targeted at extracting and returning the first element of the array.

For example:

w3docs logo Javascript arrays shift element
let books = ["Html", "Css", "Javascript"]; console.log(books.shift()); // remove Html and show it console.log(books); // Css, Javascript

unshift

This one is used to add the element to the beginning of the array, as follows:

w3docs logo Javascript arrays unshift element
let books = ["Css", "Javascript"]; books.unshift('Html'); console.log(books); // Html, Css, Javascript

With the help of methods push and unshift, you can simultaneously add different elements.

Let’s have a look at this example:

w3docs logo Javascript arrays push and unshift element
let books = ["Html"]; books.push("Css", "Javascript"); books.unshift("Php", "C#"); // ["Php", "C#", "Html", "Css", "Javascript"] console.log(books);

Internals

As we mentioned above, arrays are a special type of object. Square brackets can be used to access a property arr[0] come from the syntax of the object. One thing makes an array even more special. It’s their internal representation. The engine tends to store its elements consecutively in the contiguous memory area. But, note that they will break if you quit to work with the array in the given order and deal it as an ordinary object.

For example, it is technically possible to act like this:

let books = []; // make an array 
books[99999] = 5; // assign a property with the index far greater than its length 
books.name = "Javascript"; // create a property with an arbitrary name

It is available because arrays are objects. You have the option of adding properties to them.

You should also know the cases of the array misuse to avoid them. Here are several examples:

  • Adding a non-numeric property, such as arr.test = 9.
  • Making holes, like add arr[0] and then arr[500] putting nothing between them.
  • Filling the array in the reverse order. For example, arr[500], arr[499].

We can assume that one should treat arrays as unique structures working with them with the ordered data.

Loops

One of the common ways of cycling array items is the for loop over indexes.

Here is an example:

w3docs logo Javascript arrays loop
let arr = ["Html", "Css", "Javascript"]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }

Another form of loop is for..of.

The example looks like this:

w3docs logo Javascript arrays loop
let books = ["Html", "Css", "Javascript"]; // iterates over array elements for (let book of books) { console.log(book); }

This form of the loop doesn’t give access to the number of the current element.

As arrays are objects, also you can technically use for..in:

w3docs logo Javascript arrays loop
let booksArray = ["Html", "Css", "Javascript"]; for (let key in booksArray) { console.log(booksArray[key]); // Html, Css, Javascript }

Anyway, it’s not a good idea, as it can cause potential problems, such as:

  • The loop for..in may iterate over all the properties, not only the numeric properties.
  • The loop for..in is optimized for generic objects but not arrays. That’s why it’s up to 10-100 times slower.

The Length

Whenever we modify the array, the length property automatically updates. It’s not the count of values in the array, but the numeric index + 1. For example, a single element with a large index will give a great length, like this:

w3docs logo Javascript arrays length
let books = []; books[100] = "Html"; console.log(books.length); // 101

Anyway, developers don’t use arrays in that way.

The length property is writable. When you decrease it, the array will be truncated. Let’s have a look at this example:

w3docs logo Javascript arrays length
let arr = [1, 2, 3, 4, 5]; arr.length = 3; // truncate to 3 elements console.log(arr); // [1, 2, 3] arr.length = 5; // return length back console.log(arr[4]); // undefined: the values do not return

You can easily clear the array by using arr.length = 0;.

Creating a New Array

Here is another syntax for creating an array:

let arr = new Array("Html", "Css", "etc");

Anyway, this syntax is not used frequently.

In case a new Array is called with just one argument, that is a number. After that, it creates an array without items, but with a particular length:

w3docs logo Javascript create array
let arr = new Array(3); // will it create an array of [3] console.log(arr[0]); // undefined! no elements. console.log(arr.length); // length 3

In the code mentioned above, all elements are undefined .

Multidimensional Arrays

Arrays might have items that are arrays, as well. It can be used for multidimensional arrays to store matrices:

w3docs logo Javascript create array
let matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; console.log(matrix[1][1]); // 5, the central elementarrays

toString method

Arrays implement the toString method in their own way. It returns a comma-separated list of elements. Here is an example:

w3docs logo Javascript create array
let arr = [1, 2, 3]; console.log(arr); // 1,2,3 console.log(String(arr) === '1,2,3'); // true

There is an alternative one, as well:

w3docs logo Javascript create array
console.log([] + 1); // "1" console.log([1] + 1); // "11" console.log([2, 1] + 2); // "2,12"

But they don’t have Symbol.toPrimitive and valueOf. Arrays implement merely the toString conversion. Thus, here [] transforms into "1" and [2,1] becomes "2,1".

If the binary plus "+" operator adds something to a string, it switches it to a string so that the next step looks as follows:

w3docs logo Javascript create array
console.log("" + 1); // "1" console.log("2" + 1); // "21" console.log("2,2" + 1); // "2,21"

Do you find this helpful?