Array length in javaScript and addressing the confusion
You would think that Array length in javaScript is a trivial matter, and in some respects it might be. However on closer inspection there does seem to be more to it than what might appear to be the case on first inspection. Some might think that the number of elements in an array and the length of an array are one and the same, but that is not really the case actually depending on what you think an element is. If you think that an element can be just simply a kind of slot that can potentially be empty then maybe that is true, else it is not. In any case what I am driving at here is that arrays in javaScript are sparse in nature, and this sparse nature of javaScript arrays can result in problems and confusion if one is not aware of this, and how to go about dealing with it.
One way of thinking about array length might be that Array length in javaScript refers to the highest numbered index value of an array plus one because array length is one rather than zero relative. That is when it comes to the number index values of arrays the numbers start at zero rather than one as with the array length property so often the value of one has to be added and subtracted now in then in expressions to address problems with this. However the value can also be thought of more as just a potential for that actually, as all the elements could be empty elements as the length of an array might not always be the same as what is often called the count of an array.
So then because in some cases array length is just an object property that does not even reflect the highest indexed object key of the array, because there is nothing there actually in some situations. Then in a way it is just a way of declaring an element size of sorts, but many of those elements can be undefined, the default value for an object key that is not there.
The length differs from the size of an array which may refer to the amount of data that an array might take up in memory. There is also what if often called the count of an array that refers to the number of actual declared elements in the array, and that array count might differ in many respects depending on how you go about counting elements in the first place.
So then for the most part, on the surface at least, the length property of an array is easy to understand under a certain light. However there are a few situations that might cause a degree of confusion. So in this post on the subject of array length in javaScript I will take a moment to see about trying to clear up some of the confusion. As such this will be a lengthy post that I will be updating often.
1 - Array length basics in javaScript
For the most part array length in javaScript is a fairly simple and straight forward concept, all Arrays and Array like objects have a length property. This length property is updated each time one or more elements are added to the array, as well as when they are removed using an array prototype method like Array pop, or Array splice. However there is a difference between length, and what is often called count when taking about arrays in js. More on that later in this post, but for now lets cover the basics of array length in javaScript.
Although I will be keeping the examples in this section fairly simple, this is not a getting started type post with javaScript. I assume that you have at least some experience when it comes to getting started with the very basics of javaScript when it comes to running some code in one or more various environments.
- The source code examples and additional notes for this post are on Github
On Github I have my test vjs repository and in a folder of that repository I have the source code examples that I am writing about in this post. There are many other folders, and there all ready is, or at least sooner or later will be a folder for each of my posts on javaScript itself.
1.1 - Array length is one relative, and index values are zero relative
One of the basic concepts to understand about arrays is the nature of array index values in a javaScript programing environment. Arrays in javaScript are Objects that have a numbered set of public key value pairs. So each property of the object that is an element of the array has a numbered index value that can start at the value of zero upwards to the array length minus one.
So in other words these numbered index values are zero relative, meaning that they start at zero and go upward from there, rather than starting at one which would be one relative. So then because the length of an array is one relative, this can often result in inconsistency between length of an array and the index values of an array, however this can easily be adjusted by subtracting or adding one.
|
|
1.2 - Array length, count, and Array index
An array has a length property and in most situations the length property is also the number of actual elements in the array as well. However this is not always the case depending on how you go about counting elements. So an arrays count of elements might differ from the length of the array depending on the methodology used to count elements, or potential elements if you prefer. One way of putting it would be thinking of an empty liter sized bottle, it might be an empty bottle but it still has a capacity of one liter. The length of an array could be thought of as the liter bottle itself, and the count of an array can be thought of as whatever amount of volume of something is filling that array.
In addition to the length of an array, and the count of the elements in the array there is also the array index value. This is often a number or a string that can be easily converted to a number that reflects the index of a certain element in an array. That being said there are at least three general numerical values of interest when it cokes to working with an array then, the max capacity or array length, the element count, and the current index value when it comes to looping over the contents of an array.
|
|
In the above example I have an array that was created from an object that has numbered key value pairs, and a length property that has a value greater than the number of other keys in the object. Also the numbed keys of the object are going up by multiples of two, and there are four keys in the object aside from the length key. This hopefully helps to give a clear understanding of what the differences are between array length, count, and an index value.
1.3 - Pushing in new elements increases length
When using a method like Array.push to add new elements to an array, the length will be updated each time. In the following example I am just creating an empty array with the array literal syntax, pushing in a new element for each iteration, and also logging the current length each time.
|
|
As expected the length of the array goes from one upwards to five as I am logging the length after pushing in new elements to it. Fairly simple of course, but in some situations things can get a little confusing when it comes to adding elements to an array in other ways, as well as when removing them.
1.4 - Popping out old elements decreases length
So also as expected popping out old elements from an array will result in the length decreasing. Here again I have a very simple example where I am just removing elements from an array with the Array.pop method one at a time on each iteration of a loop. As this happens the length decreases with each iteration of the loop as elements are removed from the end of the array with Array.pop.
|
|
There are of course many other ways to remove elements from an array that will result in a decrees of length, however there are also some ways to do so that will not. This is of course where things get a little confusing and why it is important to understand the difference between array length and array count as I have covered in the previous sub section of this post on length, count and index values of an array in javaScript.
1.5 - Setting an array element to a high index value will set the length of the Array
ANother way to end up setting array length is by using the bracket syntax to set a numbers index value higher than the current length. Take into account a basic example such as this for a moment.
|
|
Here we have an array with a length of 11, but in a way there is only six elements in the array when it comes to a basic way of counting elements. This is what I am talking about when it comes to the difference between array length and array count. The length of the array is just the highest defined index value of he array plus one, while the count of an array is the actual count of defined elements in the array.
1.6 - Array length and array count with Object.keys
So the length of an array can be found by simply taking a look at the current value of the length property of an array, but the count must be obtained by some other means such as using the Object.keys static method which can be used to get an array of public keys of any object including arrays.
|
|
The Object.keys method will work fine for a simple example such as this, but in some cases it will result in unexpected results when dealing with an array that has some additional public keys attached to it.
1.7 - length, and count is not always what is expected when dealing with associative Arrays
So say I have an array that has some elements added to it that are attached to indexed key names as usual with an array, but then some that are attached to key names that are not numbered index key values but non numbed string values. This will result in what might be an undesired array count with Object.keys.
|
|
This is because of the nature of the Object.keys method, it will give an array of all public key names of an object. In javaScript an Array is a kind of Object, so I can still do anything with it that I could with any other object such as adding additional public keys that are not numbered index values. So when trying to get the count of an array the Object.keys method might not always be the best option, more on array count later in this post.
2 - Setting the length property of an array, and Sparse array basics
It is possible to set the length property of an array by just making use of the assignment operator to given it a new length. When setting a length that is lower than the current length that will result in what would be expected which is the array will end up being truncated to that length that was set. In that event any and all elements at the index value of the length upwards will be lost. So then this can serve as a kind of way of just purging a whole bunch of elements from an index value upwards, but there are maybe better ways of doing so such as using the array splice method.
Setting a higher length property will result in a situation in which any index values above the previous length will result in being empty elements. This might result in unexpected behavior with some array methods like Array forEach or the array map method as they will skip over such elements. So in this section I will be going over a few examples of setting the length of an array, and also touch base more on sparse arrays.
2.1 - Basic set length of array example
For a basic example of setting the length of an array and what happens to an array when doing this, I have this example where I start off with a simple 1,2,3 number array. So the starting length of this array is a length of 3, and each element is defined and has a number value. When I set the length of this array to 1, the result is then all but the first element now remaining in the array. If I then set the length of the array back to a higher value then that of the current length of 1, lets say 5, then the result is a sparse array. The array is sparse because the length of the array is 5, but it is now only element index 0 that is defined, the remaining elements are not event undefined then are not defined, and as such they are just empty element locations.
|
|
2.2 - Having a print method using array for each, and setting length
To get a better idea of why this will cause problems try using an array prototype method such as the array for each method, and see what happens. The result will be that the array for each method will not call the function it is given for any and all empty element locations.
|
|
3 - Array length when making an array from an object
So in javaScript Arrays are created with the Array constructor, or more often the Array literal syntax. The way that arrays or array like objects are structured is one or more numbered key value pares with a corresponding length property that is often the element count of this kind of object.
3.1 - The array from method
The array from method is on way to go about creating an array from a plain object that is formated like an array in terms of the own properties of the object.
|
|
Understanding this can help eliminate confusion with some situations in which the length of an array is in fact really not the length of the array. In this section I will cover some more examples like this to help elaborate more with this.
3.2 - Just a length property with empty elements
It is possible to have an array that has a set length, but all of the elements are undefined. This is the case if the array is created from an object that just has a length property. A similar situation can happen if the array is created with the Array constructor syntax and given an argument that will be the length of the array.
|
|
Yet another good example of why it is that length differs from the actual element count of an array.
4 - Negative index values
It is possible to set negative index values for an array. When doing so this might result in unexpected length values as negative index values will not be counted.
However as long as the index values are enumerable the Object.keys method can be used to get an array of enumerable keys for an object, including possible negative index values. Which would be one way to get the true index value if these negative index values are to be counted.
5 - Array count, and ways of getting an actual element count
Say you are dealing with an object that also has some named object keys, and a single index value that is way ahead of the others which results in one or more empty element index positions. As I have covered in a previous section the length property of an array in javaScript is often just the highest index value plus one, however in some cases it is not even that it is just a property of an object actually. In other words it is possible to have an object with just a length property of say 5, but no numbered public keys, so in that case we are dealing with an array that has a length of 5, but a count of 0. This is true if we define the count of an array as the number of public numbered keys between and including, zero to one less the length of an array that are defined keys that contain a value that can even be the undefined value. The reason why is because a key can be define, but contain a value that is undefined actually.
However there are a number of ways to go about getting the actual count of elements in an array, and the meaning of what a count is to begin with can change to mean a whole bunch of different things actually. So in this section I will be taking a stab at all the various kinds of way that one count define what a “count” if an array could be.
5.1 - Object.keys and Object.values
There are two static methods of the main Object Object in core javaScript that in most cases will work okay for getting element count, but there are some drawbacks to be aware of.
|
|
The Object.keys method can be used to get an array of enumerable key names of an object, and the Object.values method can be used to get an array of the corresponding values. Then there is Object.getOwnPropertyNames that can be used to get all of the objects own Property names even ones like length, and any additional key value pairs that are set to be not enumerable.
One drawback to using these methods as a way to obtain element count of an array is that if some additional named properties are added to the array that will effect the count, to resolve this a method that involves just counting the positive numbered keys of the array.
5.2 - Just loop for Array count
So one way of getting actual element count that comes to mind is to just loop from zero to the length of the array of vice versa and preform some kind of condition for each for each potential element to determine if there is actually something there or not.
|
|
This presents some issues of concern when it comes to arrays with a length property that might be set to a very high number for example. It is a silly waste of resources to loop over all those undeclared numbered key values, when I could find some way to just filter a list of declared key values that can be obtained via the Object.keys static method.
5.3 - Get Array count with Array.filter
So another way to get the actual count of an array would be to still use a method like Object.keys, but filter the results of that method. The Array filter method could be used as a way to create an array of Object keys that are numbered keys equal to or grater than that of zero. The length of that array could then be used as a way to determine the count or an array.
|
|
The expression could be tweaked to preform additional checks such as weather or not object keys that are declared but set to undefined should be counted or not.
6 - Typed Arrays and length
When working with typed arrays the length property refers to the number of bit sized units the array is. For example if it is a Unit16Array and it has 3 elements the length of it is 3, and the byte length of it is 6.
|
|
The length of an array generally refers to the number of elements, or the highest index value plus one. It does not always refer to the the size of the array in terms of data.
7 - The delete operator and Array length
So in javaScript there is the delete operator which can be used to delete object properties. Once might thing that using it might effect array length, but it does not. It would seem that it is no different from just setting an array element to undefined. So then it does not behave as one might expect when it comes to using the delete keyword to remove elements from an array.
|
|
This is of course a very untypical way of deleting elements from an array though. In fact I can not say I use the delete keyword very often, in fact at all in just about any project so far.
7.1 - Deleting a source object property will effect length sometimes though
Although using the delete keyword to delete an array element will not effect length, deleting a property of an object that will be used to create an array might effect the resulting length of that array.
|
|
8 - Conclusion
So in javaScript array length is fairly easy to understand, but there are some things about it that can result in some confusion. There can be a difference between the length of an array and the actual element count for example. The length property is really only just a property of an object that reflects the highest element index of the array, and the array could be nothing but empty elements. There are also many little tricks about array length when it comes to setting the value of the length property of an array as a way to delete unwanted elements at the end of an array, and atypical ways of creating arrays fro plain old objects that juts have a length property.
In nay case I hope you enjoyed this post on array length in javaScript, I am sure that I have still managed to not cover everything when it comes to array length in javaScript alone, let alone the subject in general. If you have anything of relevant interest to add be sure to bring it up in the comments if you feel compelled to do so. Thank you for reading.