Get the first element of array in JavaScript

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.


var studentDetails=
var firstObjectValue = "";
if(studentDetails.length > 1){
   for(var index=0;index< studentDetails.length;index++){
} 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.


This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo184.js