Skip to main content

Arrays

@serverSerrverlesskiy

To store ordered collections, there is a special data structure called an Array.

Storage

Array - an ordered collection of data, which contains the 1st, 2nd, 3rd elements, etc. For example, we need it to store πŸ“¦ a list of something: users, products, site elements, etc.

Creation​

create

There are 2️⃣ options for creatingπŸ—οΈ an empty array:

let arr = new Array(5)
// new Array(5) - creates an array with no elements (which cannot be accessed just like that), but with a given length.
let arr = []

The second variant 2️⃣ syntaxπŸ“– is almost always used. In parentheses, we can indicate the initial values of the elements:

Live Editor
Result
Loading...

The array elements are numbered starting from zero 0️⃣.

We can get an element by specifying its number in square brackets πŸ‘‡:

Live Editor
Result
Loading...

We can replace the πŸ–ŠοΈ element:

fruits[2] = 'Plum' // now ["Apple", "Orange", "Plum"]

... Or add πŸ†• a new one to the existing array πŸ‘‡:

Live Editor
Result
Loading...

length​

The total number of elements in the array is contained in its .length property:

Live Editor
Result
Loading...

The length property is automatically updated when the array changes. To be precise, it is not the number of elements in the array, but the largest numeric index plus one.

Update

For example, the only real element with a large index gives the largest possible length to the array πŸ‘‡:

Live Editor
Result
Loading...

Note that we usually don't use arrays this way.

Another interesting fact about the length property is that it can be overwritten.

If we manually increase βž• it, nothing interesting happens. But if we decrease it, the array will become shorter. This process is irreversible, as we can understand from the example πŸ‘‡:

Live Editor
Result
Loading...

So the simplest way to clear the array is with arr.length = 0.

Item types​

Storage

An array can store πŸ“¦ elements of any type - number, boolean value, strings, objects, or entire functions:

For example πŸ‘‡:

Live Editor
Result
Loading...

Note result1 = arr [3] contain the text of the function, and result2 = arr [3] () the result of the executed function is () we run it.

Methods push / pop​

binarycode

Stack is a variant of using arrays as data structures.

It supports two 2️⃣ types of operations:

  • push adds a βž• element to the end.

Add

  • pop removes βž– the last element.

Delete

Thus, new elements are always added or removed from the "end".

An example of a stack is usually a pyramid: new rings are placed on top and also taken from above.

Queue is one of the most common uses for an array. In computer science, this is an ordered collection of elements

Methods for working with the end of an array:​

push​

Add to

Adds an βž• element to the end of an array πŸ‘‡:

Live Editor
Result
Loading...

pop​

Delete

Removes βž– the last element from an array and returns it πŸ‘‡:

Live Editor
Result
Loading...

Methods for working with the beginning of an array:​

start

shift​

Removes βž– the first from the array and returns πŸ”„ it:

delete

Live Editor
Result
Loading...

unshift​

Adds an βž• element to the beginning of the array:

Plus

Live Editor
Result
Loading...

The push and unshift methods can add βž• several elements at once πŸ‘‡:

Live Editor
Result
Loading...

Internal Array​

cupboard

An array is a special kind of object. The square brackets used to access the arr [0] property are essentially the usual syntax for key access, such as obj [key], where obj is arr and the key is a numeric index.

Arrays extend objects because they provide special methods for working with ordered collections of data, as well as a length property. β€œBut they are still facility based.

Keep in mind that in JavaScript, an array is an object and therefore behaves like an object.

For example, an array is copied by reference πŸ‘‡:

Live Editor
Result
Loading...

What really makes arrays special is their internal representation. The JavaScript engine tries to store the elements of an array in a contiguous region of memory, one after the other. There are other optimizations that make arrays very fast.

But they all become ineffective if we stop working with an array as an "ordered collection of data" and start using it like a regular object.

For example, we can technically do the following:

let fruits = [] // create an empty array

fruits[99999] = 5 // create a property with a redundant index much larger than the required array length

fruits.age = 25 // create a property with an arbitrary name

This is possible because the array is based on an object. We can assign any properties to it.

Possible misuse of an array!
  • Adding a non-numeric property (index test), for example: arr.test = 5
  • Creation of "holes", for example: adding arr [0], then arr [1000] (there is nothing in between)
  • Filling the array in reverse order, for example: arr [1000], arr [999], etc.

Consider an array as a special structure that allows you to work with ordered data. If you need arbitrary keys, it is quite possible that a regular {} object is better suited.

Efficiency​

Fast

The push / pop methods are fast, and the shift / unshift methods are slow.

Why is it faster to work with the end of an array than with its beginning? Let's see what happens at runtime:

fruits.shift() // remove the first element from the beginning

It is not enough to simply grab and remove item 0. You also need to re-number the rest of the elements.

The shift operation has to do 3 things:

  • Remove element with index 0

Delete

  • Move all the elements to the left, re-number them, replacing 1 with 0, 2 with 1, etc.

Move

  • Update the length property

The more elements the array contains, the longer it will take to move them, the more memory operations.

But what about removing pop? He doesn't need to move anything. To remove an element at the end of an array, the pop method clears the index and decrements the length. The rest of the elements remain with the same indices.

fruits.pop() // remove one element from the end

The pop method does not need to be moved. That is why it runs very quickly.

The push method works the same way.

Iterating over elements​

Object

One of the oldest ways to iterate over array elements is a for () loop over numeric indices πŸ‘‡:

Live Editor
Result
Loading...

But another version of the loop is possible for arrays, for..of πŸ‘‡:

Live Editor
Result
Loading...

The for..of loop does not provide access to the number of the current element, only its value, but in most cases this is more than enough, and it is also shorter.

Multidimensional arrays​

Matryoschka

Arrays can contain elements that are also arrays. This can be used to create ΠΎΠΌΠ΅Ρ€ multidimensional arrays, for example, to store πŸ“¦ matrices:

Live Editor
Result
Loading...

Total​

remember

An array is a special type of object designed to work with an ordered set of elements.

AnnouncementπŸ—£οΈ:

// square brackets (usually)
let arr = [item1, item2 ...]

// new Array (very rare)
let arr = new Array (item1, item2 ...)

The call new Array (number) creates an array with the given length, but no elements.

The length property reflects the length of the array.

We can use an array as a deque using the following operations:

  • push (... items) adds βž• items to the end of the array.
  • pop () removes βž–element at the end of the array and returns it.
  • shift () removes βž– the element at the beginning of the array and returns it.
  • unshift (... items) adds βž• items to the beginning of the array.

To iterate over the elements of an array:

  • for (let i = 0 i < arr.length i ++) - works fastest, compatible with older browsers.
  • for (let item of arr) - modern syntaxπŸ“– only for item values ​​(no access to indices).
  • for (let i in arr) - never use for arrays!

Problems?​

Problem

Write to Discord chat.

Questions:​

Question

An array is ...

  1. Subtype of objects with "ordered collection of data"
  2. Internal function
  3. Subtype of objects with "unordered data collection"

An empty array is created:

  1. let arr1 = []
  2. let arr2 = {}
  3. let arr3 = ()

The length of the array can be determined by the property:

  1. pop ()
  2. push ()
  3. length

The array can store elements:

  1. Any type
  2. Numeric
  3. String

Adding an element at the end of the array:

  1. push ()
  2. pop ()
  3. shift ()

Removing an element at the beginning of an array:

  1. pop ()
  2. shift ()
  3. unshift ()

In order to understand how much you learned this lesson, take the test in the mobile application of our school on this topic or in our telegram bot.

JS Camp

  1. Article "Arrays"
  2. MDN web doc. Article "Arrays"
  3. JavaScript Arrays
  4. Code for Teens: The Perfect Beginner's Guide to Programming, Volume 1: Javascript - Jeremy Moritz

Contributors βœ¨β€‹

Thanks goes to these wonderful people (emoji key):


Dmitriy K.

πŸ“–

Dmitriy Vasilev

πŸ’΅

Resoner2005

πŸ› 🎨 πŸ–‹

Navernoss

πŸ–‹ πŸ› 🎨

Become a Patron!