Get the first element of array in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

You can use simple for loop along with some if else condition to get the array’s first element in JavaScript.

The logic is that, first of all check the array length is greater than 1 or not if the length is not equal to 1 that means there is no element in the array. So, go to the else condition and set the value undefined and print any message at the console. If there is an element in an array, set the first index value to any variable and terminate the loop with the help of break and print the message at the console.

Example

var studentDetails=
[
   {
      "firstName":"John"
   },
   {
      "firstName":"David"
   },
   {
      "firstName":"Bob"
   },
   {
      "firstName":"Mike"
   },
   {
      "firstName":"Carol"
   }
]
var firstObjectValue = "";
if(studentDetails.length > 1){
   for(var index=0;index< studentDetails.length;index++){
      firstObjectValue=studentDetails[index].firstName;
      break;
   }
} else {
   firstObjectValue=undefined;
}
if(firstObjectValue!=undefined)
   console.log(firstObjectValue);
else
console.log("There is no element in the array");

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo184.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo184.js
John
raja
Published on 14-Sep-2020 06:42:21
Advertisements