Arrays in js are different from arrays in other programming languages like Java and C++. Let’s see how:
- Arrays in Java and C++ are static.
- Arrays in js are dynamic.
Arrays in Java and C++ are static
Arrays in Java and C++ are static. It means they have fixed size.
class Main {
public static void main(String[] args) {// create an array of size 3
String avengers[] = {“Ironman”, “Antman”, “Thor”};// not possible
avengers[3] = “spiderman”;
System.out.println(avengers[3]);
}
}
Here,
// create an array of size 3String avengers[] = {“Ironman”, “Antman”, “Thor”};
Creates an array of length 3.
As the arrays in java are fixed in size, we cannot add more than 3 items in the array.
As you can see, there is no space after the last element of the array. So, it is not possible to add other elements there.
Even if the space is available, it is not possible to add elements to the array.
So, how do we add elements?
To add the elements we create a new array of size 4. Copy all the elements to the new array and add the new element.
However, we might want to add more elements to the array. So, to be on the safer side, we create an array of double the size.
Arrays in js are dynamic
Arrays in js can have as many elements as we want. Arrays in js are actually objects. Where the indexes are key and the elements are values.
// create an array of size 3const avengers = [“Ironman”, “Antman”, “Thor”];// add element to array
// possibleavengers.push(“Spiderman”);console.log(avengers);