JavaScript Arrays and the 3 Things You Should Know

Arrays are common in programming; they are special types of variables that can hold many values at once. But JavaScript has some unique array features that aren’t widely known.

In this blog, we’ll dive into three lesser-known but significant aspects of JavaScript arrays that may be new to you.

1. Adding Custom Features to Arrays

When you dive deep into JavaScript arrays, you’ll realize that at their core, they’re essentially objects.

Most things in JavaScript are actually objects. There are primarily two data categories in JavaScript: primitives and objects. But even primitives eventually get wrapped inside objects.

Entities like Array, Function, and Date are all predefined JavaScript objects. They come with their methods, properties, and a standard structure.

Specifically, JavaScript arrays can have three types of properties:

  1. Indices which are part of any array
  2. Default properties given by JavaScript
  3. Custom properties that you can personally add

While most are familiar with the first two, we’ll quickly overview them before diving into how you can include your own custom property.

Understanding Indices as Properties

In JavaScript, arrays use the square bracket syntax, like var fruitsArray = ["orange", "apple", "lychee"];.

Here, indices of array elements act as properties, and these property names are always positive integers. It’s a lot like how objects have a key-value structure.

You can think of the array index as the object’s key. And just like you can set an object’s key, you can also set an array’s index. For example, fruitsArray[3] = "peach";.

Using Built-in Properties

Arrays come with some built-in properties, like array.length. This property, for instance, indicates an array’s length.

These default properties are commonly found in many of JavaScript’s predefined objects. They, along with some built-in methods, are what make these objects versatile for various uses.

You can access these properties either using the object.property or object["property"] syntax. So, fruitsArray["length"] will give you the length of the array.

How to Add Your Custom Properties

Now, onto the fun part: adding your own properties to arrays. Though arrays are designed to store values at different indices, you might sometimes want to add some custom properties.

Usually, beginners aren’t introduced to this feature because it’s not frequently used. If you’re looking to add key-value pairs to an array, you might as well use a regular object. However, there can be cases where adding a custom property to an array can be handy.

For instance, you could add a custom property to identify the “type” or “group” of its elements, as shown in the example below:

 var fruitsArray = ["orange", "apple", "lychee"];
 fruitsArray.typeOfItems = "fruits";
 
 console.log(fruitsArray + " are " + fruitsArray.typeOfItems);
 // "orange,apple,lychee are fruits"

Remember, any custom property you add to an array will be enumerable. That means, it’ll show up when using loops like the for…in statement.

2. Iterating Through Array Elements

Many might say, “I’ve got this covered,” when it comes to looping through arrays. While that’s often true, it’s important to note that when we talk about looping through arrays, we’re essentially looping through their indices.

Since array indices are exclusively non-negative integers, the typical method involves iterating from zero up to the array’s length. During each iteration, the current index is used to access the corresponding array element.

However, with the advent of ECMAScript 6 (ES6), we gained a more direct method to loop through array elements, bypassing the indices. This is achieved 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 the context of arrays, the for...of loop traverses through the array elements, respecting their index order. Essentially, it handles the index iteration and fetches the corresponding array value at each step. This loop is particularly useful when you need to process all the elements in an array.

 var fruitsArray = ["orange", "apple", "lychee"];
 
 for (let fruit of fruitsArray){
     console.log(fruit);
 }
 // Output: "orange", "apple", "lychee"

Contrast this with the classic for loop, where the iteration is over indices rather than values:

 var fruitsArray = ["orange", "apple", "lychee"];
 
 for (var index = 0; index < fruitsArray.length; index++){
     console.log(index);
 }
 // Output: 0, 1, 2

3. Array Length vs Number of Elements

It’s a common misconception that an array’s length is always equal to the number of elements it contains. In truth, the length of an array is determined by its highest index, not necessarily the quantity of its elements.

The length property of an array is quite adaptable. Regardless of whether you’ve set the array’s length beforehand, adding more elements will increase the length correspondingly.

 var myArray = [];
 myArray.length = 3;
 console.log(myArray.length);
 // 3
 
 myArray[5] = "abcd";
 console.log(myArray.length);
 // 6

In the example above, despite only adding one value at index 5, the array’s length expands to 6. It’s important to note that no indices from 0 to 4 are actually created in this process. This can be verified using the in operator.

 var myArray = [];
 myArray.length = 3;
 console.log(myArray.length);
 // 3
 
 myArray[5] = "abcd";
 console.log(myArray.length);
 // 6
 
 console.log(0 in myArray);
 // false

The array myArray is what’s known as a “sparse” array, characterized by non-continuous indices and gaps between them. This is in contrast to a “dense” array, where indices are continuous and the number of elements equals the length property.

The length property can also truncate an array, ensuring the highest index is always less than the length itself. This is because the length is, by default, numerically greater than the highest index, as detailed here.

In the following example, observe how decreasing the length of array myArray leads to the loss of the element at index 5.

 var myArray = [];
 myArray.length = 3;
 console.log(myArray.length);
 // 3
 
 myArray[5] = "abcd";
 console.log(myArray.length);
 // 6
 
 myArray.length = 2;
 console.log(myArray.length);
 // 2
 
 console.log(myArray[5]);
 // undefined

Further Reading

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail