Last updated on October 18, 2022
In an array, we are allowed to store multiple values or data items. For example, we have a list of names like “Apple, Banana, Grapes, Mango” etc. These names can be stored in a single variable.
var fruits = ['Apple', 'Banana', 'Grapes', 'Mango'];
In this example, we stored all fruits’ names in a single variable. we can use different methods to access the specific value from the array.
The array can hold many values and those values can be accessed using an index number. In the array, every value has an index number starting from 0; in the fruits array apple is on index 0, banana index 1, grapes index 2, and mango index 3.
We can access those values with their index number like the below example.
console.log(fruits[1]);
// output: Banana
console.log(fruits[0])
// output: Apple
console.log(fruits[2])
//Output: Grapes
console.log(fruits[3])
//Output: Mango
In the case of accessing any specific value, we can use its index number.
We can change the value of the array. For example, in the fruit array, the apple needs to replace with an orange.
var fruits = ['Apple','Banana','Grapes','Mango'];
fruits[0] = 'Orange';
console.log(fruits);
// Output: (4) ['Orange', 'Banana', 'Grapes', 'Mango']
In the above example, apple is replaced with orange, using index number, in this way we can change any array value by index number.
We can check how many values are in the array. For example, we would like to know how many values are in the fruit array. So the .length property will print the last highest index.
var fruits = ['Apple','Banana','Grapes','Mango'];
console.log(fruits.length);
// output: 4
We can access all values of the array using an index number, but in the case of large data, it is impossible to write the index number with every value, for accessing all values we use a loop that writes the index number with every value within microseconds and print the values.
var fruit = ['Apple','Banana','Grapes','Mango'];
for(var i=0; i<fruit.length; i++){
document.write(fruit[i]+', ');
}
// Output: Apple, Banana, Grapes, Mango,
In the above example, an array printed by the loop, we write the number using the JavaScript loop and then print the values.
The array is a single variable that can hold too many values, we can access those values using index numbers and can print a full array or a specific array value using the index number, also we can print the array using a loop and can shuffle the array values.