In JavaScript an array is a useful tool for storing multiple data even of different types.
In fact, JavaScript, like other programming languages, allows the creation and management of arrays.
There are various ways to define an array in JavaScript, in this tutorial we will analyze them all and see which is more congenial.
JavaScript array – definition
First, let’s study the methods for defining an empty array.
First method to definition an array
The first method we analyze to define an empty array is the use of the Array () object.
This method follows the following syntax:
var photo = new Array();
So the photo variable is an array defined using the new constructor.
In this way the Array() object is exploited.
Second method to definition an array
You can also not use the new constructor to create an empty array, so you can also just write:
var photo = [];
JavaScript array – data entry
We can put the data into an array with multiple methods.
First method to insert data in array
Following the first method, we can assign the elements directly within the round brackets of the Array () object.
var photo = new Array(“img1.jpg”,”img2.jpg”,…);
Second method to insert data in array
The second method is the most used when we need to initialize an array with predefined elements and allows you to insert each element separated by commas:
var photo = [“img1.jpg”, “img2.jpg”, …];
Alternatively, you can create an empty array and then assign the elements:
var photo = [];
photo[0]=”img1.jpg”;
photo[1]=”img2.jpg”;
JavaScript array – read data
Now let’s see how to read data from an array.
Populate an array with the days of the week and print all elements.
In this lesson we will see how to print the elements without using the for loop and the length property, the subject of the next lessons.
So we put the days of the week in an array named days.
var days = [“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”];
After considering that the first element has index 0 and the others to follow have an increasing index, we print each element simply in this way:
console.log(days[0]); ....
Here is the complete script:
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
console.log (days [0]);
console.log (days [1]);
console.log (days [2]);
console.log (days [3]);
console.log (days [4]);
console.log (days [5]);
console.log (days [6]);
Of course, you can use a loop to read the entire array, but we will analyze it in the next lessons.
In this lesson we have studied some very simple examples of arrays in JavaScript, in the next lessons we will study the various methods necessary to perform some operations.
Conclusion
In this lesson we have seen how to create a JavaScript array, how to insert data and how to read it.