JavaScript Arrays Demystified: A Quick Guide for Beginners
Array:
An array is a special data type in JavaScript used to store multiple values of the same type or of different types under a single name.
Example:
const myFavFruits = [“Mango”, “Banana”, “Pomegranate”];
console.log(myFavFruits);
In this example, I have created an array, myFavFruits, and assigned it the values Mango, Banana, and Pomegranate. Then, using the statement console.log(myFavFruits), I have printed my array.
Output:
[ ‘Mango’, ‘Banana’, ‘Pomegranate’ ]
Accessing Elements of an Array: We can put several elements in an array, so if we want to access a specific element, we can access it through its index. The index of the array starts from 0. The element at the beginning of the array has an index of 0, the element at the second position has an index of 1, and so on.
Example:
const myFavFruits = [“Mango”, “Banana”, “Pomegranate”];
console.log(myFavFruits[1]);
Output:
Banana
In this example, I have accessed the element present at index 1, which is Banana, so it will give the output Banana. If I write an index that is not present in the array, like in my example, where I have indexes of 0, 1, and 2, and I try to access the element at the third index, it will give me an output of undefined which means value for this index has not been defined yet.