Arrays
To store ordered collections, there is a special data structure called an Array
.
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
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:
The array elements are numbered starting from zero 0️⃣.
We can get an element by specifying its number in square brackets :
We can replace the element:
fruits[2] = 'Plum' // now ["Apple", "Orange", "Plum"]
... Or add a new one to the existing array :
length
The total number of elements in the array is contained in its .length
property:
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.
For example, the only real element with a large index gives the largest possible length to the array :
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 :
So the simplest way to clear the array is with arr.length = 0
.
Item types
An array can store elements of any type - number, boolean value, strings, objects, or entire functions:
For example :
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
Stack
is a variant of using arrays as data structures.
It supports two 2️⃣ types of operations:
push
adds a ➕ element to the end.
pop
removes ➖ the last element.
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
Adds an ➕ element to the end of an array :
pop
Removes ➖ the last element from an array and returns it :
Methods for working with the beginning of an array:
shift
Removes ➖ the first from the array and returns it:
unshift
Adds an ➕ element to the beginning of the array:
The push
and unshift
methods can add ➕ several elements at once :
Internal Array
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 :
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.
- 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
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
- Move all the elements to the left, re-number them, replacing
1
with0
,2
with1
, etc.
- 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
One of the oldest ways to iterate over array elements is a for ()
loop over numeric indices :
But another version of the loop is possible for arrays, for..of
:
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
Arrays can contain elements that are also arrays. This can be used to create омер multidimensional arrays, for example, to store matrices:
Total
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?
Write to Discord chat.
Questions:
An array is ...
- Subtype of objects with "ordered collection of data"
- Internal function
- Subtype of objects with "unordered data collection"
An empty array is created:
let arr1 = []
let arr2 = {}
let arr3 = ()
The length of the array can be determined by the property:
pop ()
push ()
length
The array can store elements:
- Any type
- Numeric
- String
Adding an element at the end of the array:
push ()
pop ()
shift ()
Removing an element at the beginning of an array:
pop ()
shift ()
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.
Links
- Article "Arrays"
- MDN web doc. Article "Arrays"
- JavaScript Arrays
- 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 🖋 🐛 🎨 |