You can use Array to store multiple values in a single variable.
Example : Suppose, You have a list of Fruits then for each Fruit you have to create a new variable so with the help of Array you can store the names of All Fruits in a Single Array.
Advantages of using Array
- Store Multiple Values in a Single Variable.
- Every Item has a Index by which you can access to that value.
- You can Store as many Values as you want.
It is the Unique Position Number of the Values you have assigned in Array.
In Every Array Index Starts from 0.
For 1st Value index is 0 , For 2nd Value index is 1, For 3rd Value index is 2 and So on.
We have Declared fruitName array and have stored names of 5 Fruits.
Then, we have printed fruitName with index 0 in the Console Tab.
Let me explain the index :
In array, Index is the ID of the Value stored in a array, indexing starts from 0, 1, 2, 3 .......
Total No. of Elements are 5
Change the Value of Array
To Change the Value, We want to know the index of element and store the new value to that index
We are changing the value of fruitName array with index 1 i.e. Banana and Changing it to Strawberry.
You can find out how many elements an array has, using the length property:
In this example, we are trying to get the Last Value of Array without knowing the index.
We have declared fruitName array with 5 Fruits Stored in it.
length variable stores the length of the fruitName array i.e. 5
Then, We are storing value of fruitName[length - 1] to lastFruit variable.
i.e. fruitName[5-1] ⇒ fruitName
Why we subtracted 1 to the array length? because, indexing of variable starts from 0 and fruitName.length gives 5
Lets Understand this in Tabular Form
Printing All Elements of 1-D Array.
We, will be using for Loop
There is one more way to Loop through the elements of the Array.
By using For...of Loop.
Loop will iterate from starting to the End Elements of the Array.
That Means, For Each Element of the Array statements will be executed.
Did you see the difference?
Now we don't have to find the length of the array. for...of Loop will Execute for Each Element of the Array.