Storyline
I recently learned about HashMaps and how they are implemented and encountered something fascinating about arrays.
It was an interesting quirk about initialising arrays. So, I shall tell you about it.
What is an Array?
An array is a data structure that allows you to store ordered collections of items of the same or varying types in the same variable. These items it stores can, in turn, be arrays. It is handy because you can iterate through arrays and transform the elements, allowing for a lot of dynamic computation on the elements of the array.
How do you create an array in js?
There are primarily 2 ways of initialising an array in js - Using the array literal and using the array constructor. This article is about something i recently discovered while using the array constructor so lets look at that last.
The array literal is used to initialise arrays in this manner
// Literal notation examples
const arrLit1= [];
const arrLit2= [1,2, 'two', 'joe', true];
const arrLit3= [1, 2, 3, 4, 5, 9];
// new Array constructor examples
const arrCon1= new Array();
const arrCon2= new Array(1,2, 'two', 'joe', true);
const arrCon3= new Array(1, 2, 3, 4, 5, 9);
What you came here for
The above examples are equivalent and get the same results, i.e. arrCon1 is equivalent to arrLit1, and so on.
But take a look at this -
const arrLit4= [5];
const arrCon4= new Array(5);
Do you think they are equivalent? I am sure you guessed since I am asking, they are probably not equivalent and that is right. They are not equivalent - they will not yield the same result. arrLit4 creates an array with one lement, 5, and arrCon4 is an array of size 5 where all the elements are undefined.
Let's break this down further. The Array constructor has an interesting function signature. Depending on what collection of parameters are passed in, it behaves a bit differently. If you pass in a single integer parameter between 0 and 2pow32 - 1 (inclusive), it creates an array of that size. Every element at every index is undefined until you populate it with something else. However, give it more than one integer, a negative integer, a single element of any other type, or multiple elements of any other type (including positive integers), and it will create a new array with those elements that you gave it as a parameter.
Side note: In computer science, the concept of having a function/method, which, when called with specific parameters, behaves in one way but, when given a differing type or number of parameters, behaves differently is called method or function overloading. Side side note: Function overloading in the traditional sense is not possible in JavaScript, but with some trickery, the same result can be achieved. If it walks like a duck, swims like a duck, and quacks like a duck, then ....
What about the examples below? Are they equivalent?
const arrLit5= ['Lorem Ipsum'];
const arrCon5= new Array('Lorem Ipsum');
Yes, they are. Even though the new Array constructor has a single parameter passed in, it is not an integer between 0 and 2pow32 - 1 (inclusive). Thus, both examples create an array with a single string element, 'Lorem Ipsum'.
In Javascript, arrays are dynamic—their sizes can be changed on the fly. This is not the case in all programming languages. For example, in Java or C, when you declare an array, you have to declare a size, and when it reaches max capacity or you need more space, you create a new, bigger array to accommodate your needs.
So, when you initialise an array in JavaScript with the constructor style, you can still add to it even when you reach the limit. It will expand to accommodate the new elements behind the scenes.
Here is an example -
const arrSizeTwo = new Array(2);
console.log(arrSizeTwo.length); // 2
console.log(arrSizeTwo); // [ <2 empty items> ]
console.log(arrSizeTwo[0]); // undefined - all elements are until changed.
arrSizeTwo[0] = 'Element 1';
arrSizeTwo[1] = 'Element 2';
arrSizeTwo[2] = 'Element 3'; // Adding an element beyond the initial length
console.log(arrSizeTwo.length); // 3
console.log(arrSizeTwo);
On the contrary, here is an example in Java where you have to create a new, larger array if you need more space.
public class Main {
public static void main(String[] args) {
int[] arrTwoJava = new int[2]; // Array with length 2
arrTwoJava[0] = 1;
arrTwoJava[1] = 2;
// arrTwoJava[2] = 3; Error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
// Instead, we need to create a new array with a larger size
int[] arrThreeJava = new int[3];
System.arraycopy(arrTwoJava, 0, arrThreeJava, 0, arrTwoJava.length);
arrThreeJava[2] = 3; // Adding the new element
System.out.println(arrThreeJava.length); // 3
for (int i : arrThreeJava) {
System.out.println(i); // 1 2 3
}
}
}
Voila. I hope you learned something new: the array constructor quirk in Javascript, function overloading, and dynamic/static array sizing in programming languages.
That will be all for now.
Ciao!
Top comments (0)