Arrays are a widely-used feature of programming languages; they are special variables that can be used to store multiple values at the same time. However when it comes to JavaScript, as easy as it is to learn, there’s always more to explore.
In this post, we’ll have a look at three less well-known yet important features of JavaScript arrays you might not have known before.
1. Add Custom Properties to Arrays
If you were to scour the Internet looking for a thorough definition of JavaScript arrays, you will find that almost every source without fail will list array as what it really is, an object.
In fact, almost everything we deal with in JavaScript will turn out to be an object. There are two kinds of data types in JavaScript, primitives and objects, but primitives are always wrapped up inside objects.
Array, Function, Date, etc. are predefined JavaScript objects that have built-in methods, properties and their own standardized syntax.
JavaScript arrays can have three different types of properties:
- Indices of an array are also properties
- Built-in properties
- Custom properties you can add by yourself
The first two are more well-known, you may use them every day, but let’s see them quickly before jumping into how you can add your own custom property to an array.
Indices as Properties
JavaScript arrays use the square bracket syntax, such as var ary = ["orange","apple","lychee"];
.
Indices of array elements are basically properties where the property names are always non-negative integers.
The index-element pair of an array is similar to the key-value pair of an object.
Indices are a unique feature of the Array object, and unlike its other built-in properties, they can be set with the brackets syntax alone, such as ary[3] = "peach";
.
Built-in Properties
Arrays also have built-in properties, such as array.length
. The length
property carries an integer value that denotes the length of an array.
In general, built-in properties can be frequently found in predefined JavaScript objects like arrays. Along with the built-in methods, they help customize generic objects so that the objects are fit for different needs.
Built-in properties can be accessed with either the object.key
or the object["key"]
syntax. So you can also write ary["length"]
to access the length of an array.
Create Custom Properties for the Array Object
Now, let’s talk about adding your own properties to arrays. Arrays are predefined objects that store different types of values at different indices.
There’s usually not much need to add custom properties to an array; this is one of the reasons beginners are usually not taught about this feature. In fact, if you want to treat an array like a normal object by adding key-value pairs to it, you might as well use a normal object for your purpose. But, this doesn’t mean that there aren’t special cases where you can make use of the fact that an array is an object, by adding one or more custom properties to it.
For example, you can add a custom property to an array that identifies the "kind" or the "class" of its elements, like you can see it in the example below.
var ary = ["orange","apple","lychee"]; ary.itemClass = "fruits"; console.log(ary + " are " + ary.itemClass); // "orange,apple,lychee are fruits"
Note that the custom property you add to an array is enumerable, which means it will be picked up by loops such as the for…in
statement.
2. Loop through Array Elements
You probably say "I know that already", which is most likely true, you do already know how to go through array elements. But it is also true that saying "loop through array elements" is a bit abstract, as what we actually loop through are the indices of the array.
Since array indices are only made up of non-negative integers, we iterate an integer value typically starting from zero and ending at the full length of the array, then use that iterated value to access the array element at a given index.
However since ECMAScript6, there’s a way to directly loop through array values without bothering with indices, and that can be done by using the for…of
loop.
“The for…of statement creates a loop iterating over iterable objects (including Array, Map, Set, String, TypedArray, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property. – MDN“
In an array, the for...of
loop will loop through the array elements in the order of indices, in other words it will take care of iterating over the indices and getting an existing array value at a given index. This loop is ideal if you just want to loop through all the array elements, and work with them.
var ary = ["orange","apple","lychee"]; for (let item of ary){ console.log(item); } // "orange", "apple", "lychee"
For comparison, with the regular for
loop, we get the indices instead of the values as output.
var ary = ["orange","apple","lychee"]; for (var item = 0; item < ary.length; item++){ console.log(item); } // 0, 1, 2
3. The Number of Elements Is Not Its Length
Typically, when we speak about the length of an array, we think that it’s either the number of value an array holds, or the length we have given to the array manually. However in reality, the length of an array depends on the largest existing index inside of it.
Length is a very flexible property. Whether you’ve already fixed the length of an array beforehand or not, if you keep adding values to the array, its length keeps increasing accordingly.
var ary = []; ary.length = 3; console.log(ary.length); // 3 ary[5] = "abcd"; console.log(ary.length); // 6
In the example above, you can see that I gave the array only one value at index 5, and the length becomes 6. Now, if you think that by adding a value at index 5 , the array created the indices of 0 to 4 automatically, then your assumption is incorrect. There are really no existing indices from 0 to 4 in that array. You can check this using the in
operator.
var ary = []; ary.length = 3; console.log(ary.length); // 3 ary[5] = "abcd"; console.log(ary.length); // 6 console.log(0 in ary); // false
The array ary
is what we call a "sparse" array, an array where the indices aren’t created continuously, and have gaps. The opposite of a "sparse" array is the "dense" array where indices exist continuously in the array, and the number of elements are the same as the length
.
The length
property is also capable of truncating an array, making sure the highest index present in the array is always less than itself, as length
is always numerically greater than the highest index by default.
In the example below, you can see how we lose the element at index 5 by decreasing the length
of the ary
array.
var ary = []; ary.length = 3; console.log(ary.length); // 3 ary[5] = "abcd"; console.log(ary.length); // 6 ary.length = 2; console.log(ary.length); // 2 console.log(ary[5]); // undefined
Further Reading
- 10 JavaScript terms you should know by now
- 4 not-so-common but helpful Javascript statements you should know
- Code optimisation with JS Hint – a tool for linting Javascript
EPL Trending