Last Updated:

JS Array operations

Objects in JS are useful for data that has string keys, but are not suitable for creating a block of items ordered by number. This is due to the lack of methods for changing the order of units included in the block, adding or removing new elements with numbering correction. You can create and manipulate ordered lists of items by using arrays.

JS Array operations

Array Internals

JS arrays are sets of elements, each of which has a sequence number (index). Items can have any data type. You can also create a heterogeneous array that includes components of different types. The element coming first is assigned the number 0.


For subsequent parts of the array, the index sequence appears as an increasing series of integers starting with one. It is also possible to use negative numbers as indices - then they turn into lines represented as property names.


Arrays do not have a rigid set number of components: on the contrary, you can remove elements from them or insert new ones. No memory allocation is required.

How an array differs from an object

An array is a type of object, so the generalized properties of the second (for example, the ability to copy or change by reference) apply to the first. The syntax Arr[1], which describes the index of an element, is a variation of writing access to an object by the obj[key].

At the same time, this type of objects has a number of new characteristics, for example, a property that describes the length, as well as methods sharpened for manipulating numbered data sequences. When working with JS arrays (Arrays), you can also create a nested composition whose elements are objects or arrays.

In the second variant, the array is called multidimensional. This design is suitable for representing the matrix.

The peculiarity of this design is the way the JS engine stores data. Elements in their sequence are stored in continuous memory, which speeds up the progress of operations with them.

But if you treat the array as a simple object, all the benefits of this configuration will cease to work: the engine notices incorrect handling of the structure and reacts accordingly, turning off methods that optimize the work.

Here are examples of incorrect work with the array:

  • Create a property that has a much larger index than the number of items.
  • Layout of a list with large lacunae: for example, you first specify a component with an index of 0, then with an index of 50, and a void between them;
  • filling the list from a higher index to a smaller one (first enter Arr[50], then Arr[49], and so on).

In short, when introducing arrays into Javascript, it should be remembered that this structure is sharpened specifically for working with a numbered set of data, and use them for their intended purpose. In cases where you want to obtain arbitrary keys, a simple object is likely to be more appropriate.

It is also possible to use negative numbers as indices - then they turn into lines represented as property names.

How to create an array

The shortest and most common way to do this is to use the "let arr = [];" entry. In this case, in square brackets, you can specify the initial values of the components of the set, starting with the zero index. For example:

Let cars = [“Mercedes”, “Hyundai”, “Toyota”];

Another possible scheme is "let arr = new Array();". It is used infrequently because of the longer recording. In addition, if you call a set with a single numeric argument in this way, an empty set with a fixed length will be created. All components in such a set will be equal to undefined.

If you want to display an item with a specific number (for example, an index value of 2), use the following entry:

Let cars = [“Mercedes”, “Hyundai”, “Toyota”];
Alert( cars[2] );

The name of the toyota brand will be displayed.

The operation of replacing a component that has a certain index is implemented as follows:

Cars[2] = “Lada”;

Now in this array, containing 3 names of car brands, instead of Toyota will be located Lada.

An additional element can be added to the already formed set:

Cars[3] = “Volvo”;

As a result, the sequence will look like this: "Mercedes", "Hyundai", "Lada", "Volvo".

The length of the array array in Javascript can be called as follows:

alert( array.length );

By means of an alert, it is possible to display the elements of the set on the screen while maintaining their sequence. For example:

Let cars = [“Hyundai”, “Lada”, “Volvo”];
Alert ( cars );

The following entry will be displayed on the screen:

Hyundai, Lada, Volvo

You can store many elements of different types, for example:

Let array = [ ‘Volvo’, { name: ‘Thomas’  }, true, function() { alert(‘Hello’); } ];

Suppose your goal is to take a component of this array that has an index of 1 and display its property. To do this, the following entry is made:

Alert( array[1].name );

As a result, the name Thomas will be displayed on the screen.

Under index 3 in this ordered array is a function. To implement it, make the following entry:


As a result, Hello will be displayed.

Array length

Because the initial component always has a numeric index of 0, the length of the array in JS will not be identical to the maximum index value. If there are no empty spaces in the numbering, then to find the length, you need to add one to the last number.

If the array array is called in the JS length, the screen also displays a number one greater than the maximum index, but this will not necessarily be the length (i.e. the number of elements). This under certain conditions can lead to specific effects.

For example, if you declare an array, then specify an element with a large index number, and then call length, the value of the latter will be 1 more than that of the index, although the element that has a certain value can be only one in the array (the rest in this case will be undefined). Here's what it looks like:

Let cars = [];
Cars[1234] = “Lada”;
Alert( cars.length );

As a result, the number 1235 is displayed.

One of the features of the length parameter is the ability to increase or decrease its value. Sampling shortening is implemented as follows:

Let m = [1, 2, 3, 4, 5];
m.length = 2;
alert( m );

In this example, the array was reduced to two elements. When the updated system is displayed on the monitor, only the first two numbers out of 5 (1 and 2) will remain on the monitor. What happens if you try to return the original length?

m.length = 5;
alert( m[3] );

If you try to display the third element of the new population, you get the value undefined.

Thus, if the selection is first shortened, and then returned to its previous size, the values of the cut elements will not be restored. If the array needs to be emptied, it is easy to do so: arr.length = 0.

Itinerate through the elements

One of the classic methods to iterate through Javascript-generated arrays is a for loop that works with component indexes. It is implemented as follows:

Let herbs = [“parsley”, “sage”, “rosemary”];
For (let I = 0; I < herbs.length; i++) {
Alert( herbs[i] );


Another variant of search is also practiced - for.. of. It causes only the value of an element without its number, but in some situations this is enough. In addition, such a record is more concise. It looks like this:

Let herbs = [“parsley”, “sage”, “rosemary”];
For (let herb of herbs) {
Alert( herb );


Theoretically, you can apply the for. in:

Let herbs = [“parsley”, “sage”, “rosemary”];
For (let key in herbs) {
Alert( herbs[key] );


When withdrawing, we get the output: parsley, sage, rosemary. But the use of this cycle is not optimal and has significant disadvantages. First of all, this is a low speed, ten times inferior to other options.

It is due to the fact that the method is sharpened to work with simple objects. Another drawback is that non-digital properties are also displayed, which are usually not required.

Methods for adding and removing items

These are some of the most commonly used JS array methods. They are needed, for example, when you implement a queue, a numbered set of items for which you can add an item to the end and remove it from the beginning.

In the embodiment of the second operation, a shift in the queue occurs, as a result of which its second component becomes the first. Both of these actions can be implemented using the array's push and shift methods.

Another structure where arrays are often involved is the stack. It implements the following operations: ror (removal of the final component) and push (allows you to add the last element to the JS array). Accordingly, both the addition and cutting of components are made from the final part. In JS, you can work with an array both on a queue basis and on a stack type.

To cut the last component out of the structure and output it, use the pop method:

Let foodherbs = [“thyme”, “garlic”, “ocimum”];
Alert( foodherbs.pop() );
Alert (foodherbs );

As a result, the first two components will remain in the array. To add an element to the tail, use push:

Let foodherbs = [“thyme”, “garlic”];
Alert ( foodherbs );

To work with the beginning of an ordered set, the shift and unshift methods are used. The first of these isolates and outputs the first component:

Let medherbs = [“mint”, “leonurus”, “valeriana”];
Alert( medherbs.shift() );
Alert( medherbs );

In the example above, the first line declares a group of elements, the second deletes and displays the first of them, and the third displays the resulting array, which contains all the components except the initial one.

To add a new item to the beginning, use unshift:

Let medherbs = [“leonurus”, “valeriana”];
Alert( medherbs );

Using methods that introduce new elements, you can replenish the aggregate by several points at a time. Example with fruits:

Let fruits = [“apple”];
Fruits.push(“kiwi”, “pear”];
Fruits.unshift(“pineapple”, “lemon”);
Alert( fruits );

Other methods

To combine multiple homogeneous or heterogeneous arrays, you can use the concat() method. Here is an example of working with homogeneous aggregates – the names of birds and insects:

Var birds = [“sparrow”, “owl”, “eagle”];
Var insects = [“fly”, “louse”, “mosquito”];
Var creatures = birds.concat(insects);
For(var i=0; I < creatures.length; i++)
Console.log(creatures[i] );

For heterogeneous samples (e.g., products and their prices), the composition would look like this:

Var dairy = [“milk”, “kefir”, “cheese”];
Var prices = [30, 40, 90];
Var products = dairy.concat(prices);

To sort the sample in ascending order (if the values are in text form, alphabetically), use the sort() method. Implement it as follows:

Var fruits = [“apples”, “pears”, “pineapples”, “apricots”, “peaches”];
For(var i=0; i <fruits.length; i++);
Console.log(fruits[i] );

As a result, in the browser window, the list will be displayed as follows: apples, apricots, peaches, pears, pineapples.

There is also a reverse() method. The scheme of its execution is completely similar to the previous one (only the name changes), and the action is that the array is inverted backwards. That is, if the original set looked like this order of numbers: 1 2 3 4 5, then the new one will have the form 5 4 3 2 1.