How to get the first element of array in javascript?

by eric.hamill , in category: JavaScript , 2 years ago

How to get the first element of array in javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@eric.hamill If you know that the first element in the array is always starting from 0 you can get the first element by key 0. If you do not really sure what is the keys inside you need probably use .find(Boolean) method to get the first element of array in Javascript, here is some examples:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let arr = [1, 2, 3];
// Output: 1
console.log(arr[0]);

let array = [];
array[5] = 1;
// Output: undefined
console.log(array[0]);
// Output: 1
console.log(array.find(Boolean));

Member

by percy , a year ago

@eric.hamill 

In JavaScript, you can access the first element of an array using array notation and specifying the index of the element you want to access. The index of the first element in an array is 0. So, you can use the following syntax to get the first element of an array:

1
var firstElement = myArray[0];


Where myArray is the name of your array. You can also use array destructuring to get the first element of an array

1
const [firstElement, ...rest] = myArray


You can also use the shift() method to remove the first element of an array.

1
var firstElement = myArray.shift();


This method removes the first element from the array, and it returns the removed element.