Array and Array of Objects | A Comparison – JavaScript
Arrays in JavaScript
Arrays belong to the non-primitive data type, and as mentioned above, they are not restricted by a size constraint. This also gives them one more property, which is that they work on references, references to the memory location in which the value of their first variable is stored.
To create an array, simply create a variable and set it equal to square bracket “[ ]” and within these square brackets, type the values to store in the array, with every value separated by a comma “,”.
An example of this would be:
So, arrayVariable is the name of the array in which different types of values are being stored. Now to iterate through the elements with the help of a for loop is used and to print out the values of the array “arrayVariable” one by one, use the following lines:
console.log(arrayVariable[i]);
}
In the above lines, it is easy to notice that to access a value inside an array “square brackets [ ]” and then the index value of the elements are passed. The first element is placed at the 0th index, and the second element is placed at the 1st index, and so on. Executing this code prints out the following on the terminal:
As you can see, every element was printed on the terminal
Array of Objects in JavaScript
As mentioned before, arrays and objects are those data types that can store values of other arrays and objects. An array of objects is exactly what it sounds like, and it is an array in which every element is an object.
To demonstrate this, take the following lines of code to create two different objects in JavaScript:
name: "John Doe",
age: 18,
isEmployed: true,
};
var carObj = {
carMake: "Porsche",
price: 345000,
model: 2016,
};
Ater that, create a new array and set it equal to personObj and carObj with square brackets like:
Now, to iterate through this array and to print out its element on the terminal use the following lines of code:
console.log(arrayVariable[i]);
}
After this, the terminal will show the following:
Both of the elements of the array of objects was printed on the terminal.
To access a specific value, let the car made of the object carObj use the following line of code:
This will give the following output on the terminal:
Conclusion
JavaScript includes Array as datatypes as well as objects, now these two are able to store elements of each other. This means that creating an Array of objects is possible, as well as creating objects of arrays. In this article, a general overview of arrays and an array of objects was given with their working.
Source: linuxhint.com