To get the First Element of an Array in JavaScript, you just need to use the INDEX number 0.
Where Array indexes stars from 0 instead of 1.
my.js
const myArray = ["John", "Emily", "Rick"];
console.log("First Element is: "+ myArray[0]);
Results
We are storing our array inside the variable called myArray. By using this variable we are referencing the array stored inside this variable.
By using square brackets [ ] after the variable name, we can provide the INDEX number where [0] means that we want to get the First Element present at the INDEX NUMBER 0 postion fromt he Array.
To get the last element of the Array in JavaScript, you can use the Last Index number or automatically get it by array.length property.
But if you are using array.length property, then you need to subtract -1 from it.
Because Array Starts but 0 but .length property starts from 1.
We can easity fix it by subtracting one from it.
my.js
const myArray = ["John", "Emily", "Rick"];
//manual
console.log("Last Element is: "+ myArray[2]);
//automatic
console.log("Last Element is: "+ myArray[myArray.length - 1]);
Results
Getting array elements using loops are very easy and fast.
Loops let's you get the data automatically and is more reliable then inserting index numbers one by one.
my.js [using for loop]
const myArray = ["John", "Emily", "Rick"];
for(let i=0; i<myArray.length; i++){
console.log(myArray[i])
}
Results
In the above example, we are using for loop, where we will loop untill i=0 to array.lenth and we will increment the value of i by one using i++.
Later we can use myArray[i] and i as a dynamic index number which will return new array element on each loop run.
But if for loop is too confusing for you, then you should try array.map method.
my.js [using array.map method]
const myArray = ["John", "Emily", "Rick"];
myArray.map(elm => console.log(elm));
Results