js get first array element code example

Example 1: javascript take first element of array

const array = [1,2,3,4,5];
const firstElement = array.shift();

// array -> [2,3,4,5]
// firstElement -> 1

Example 2: get first element of array javascript

// Method - 1 ([] operator)
var arr = [1, 2, 3, 4, 5];
var first = arr[0];
console.log(first);
/*
    Output: 1
*/

// Method - 2 (Array.prototype.shift())
var arr = [1, 2, 3, 4, 5];
var first = arr.slice(0, 1).shift();
console.log(first);
/*
    Output: 1
*/

// Method - 3 (Destructuring Assignment)
var arr = [1, 2, 3, 4, 5];
const [first] = arr;
console.log(first);
/*
    Output: 1
*/

Example 3: Return the first element of the array javascript

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");

Example 4: javascript get first element of array

let mylist = ['one','two','three','last']
mylist[0],mylist[1],mylist[2],mylist[3]//this is called indexing and slicing in python
//in javascript it called getting elements in array

Tags:

Php Example