A brief introduction to JavaScript arrays
What is an array? How to create one? How to retrieve values from them? And more... just a short recap for beginners.
JavaScript arrays are objects, so they're not a separate type like in other languages. These objects hold a collection of elements. To create an empty array we got two ways. First, we can use the Array constructor.
But the preferable method is using the array literal notation.
Arrays can be initialized with some values.
We can also achieve this with the constructor
But there comes a problem with this method. Let's assume that we want to create a single element array and that element would be the number 5.
We get an array with 5 undefined elements. To fix this we can use the Array.of() method.
Much better.
We can also fill empty arrays using the fill() method.
We got an array with 4 empty elements so we filled them with 1. Filling can be also done only for certain indexes by passing two more arguments - start and end index.
JavaScript has other data structures like Maps and Sets or iterable objects like String or NodeList. We can convert them to array using Array.from().
String to Array
NodeList to Array
Set/Map to Array
As you can see in the Set/Map example - JavaScript arrays can be multi-typed and multi-dimensional. So using different types in one array is possible...
...just like creating matrices
Values from an array can be retrieved by referencing their index
Every array has its length which can be found under the length property.
length is settable which means you can resize the array by changing its value.
As you can see if the new value for length is bigger than the old one, the array will extend but all of the new values are going to be undefined.