JavaScript How get the first element of an array [Updated]

In JavaScript, if you want to get the first or last element of the array, you need to use Index numbers for that.
By using an Array Index Number, we can get the First, Second, Last, or any Array Elements easily.

my.js

var myArray = ["Element1", "Element2", "Element3"]
console.log(myArray[0])
//Index number [0] means, First Element.

Results

Element1

As you can see in the Example, we are using Index number 0, because arrays starts from 0. So if you want to get the first Element, you need to use index number [0] instead of [1].
Where [1] Means second Element from the Array.

How to get the Last Element of an Array?

If you want to get the Last Element from an Array, then again you need to use the Index number here.
Lets assume that you have an array which includes 3 Elements, So in order to select the 3rd or Last Element we need to use Index number [2] insted of [3].
Because arrays STARTS from 0. So
array[0] = first Element,
array[1] = Secound Element,
array [2] = Third Element.

my.js

var myArray = ["Element1", "Element2", "Element3"]
console.log(myArray[2])
//Index number [2] means, Third / Last Element.

Results

Element3

if you don't want to use an fixed index number, then you can also use .length property.
This .length property will calculate the Array Element length and you can use it to get the last Element easily.
Keep one thing in minde: Array starts from 0 but length counts from 1.
So you need to subtract 1 from array length in order to get the Last Element.

my.js

var myArray = ["Element1", "Element2", "Element3"]
console.log(myArray[myArray.length - 1])

Results

Element3

How to loop through an Array in JavaScript?

In order to loop through an Array in JavaScript, we need to use Loops like for loop.
Where we will loop through every array element and console.log() every element one by one.

my.js

var myArray = ["Element1", "Element2", "Element3"]

for(let i=0; i<myArray.length; i++){
    console.log(myArray[i])
}

Results

Element1
Element2
Element3

In our last Example, we are using let i = 0 to create a variable i where the inisial value going to be 0.
Next we are using i<myArray.length as our Loop condition. Which means that we want to run this loop until i's value is less the Array's length and after that we are increasing the number using i++.
and by using console.log(myArray[i]) we are logging out our Array Element One By One.

Ad

Need a Personal Tutor?

I am here to help you with your Programming journey. HTML, CSS, JavaScript, ReactJS, NextJS, C, C++, C#, SQL and more.

Just 10$/hSee Plans100% Free Trial + Money Back Guaranty
Logo