Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get the first element of array in JavaScript
In JavaScript, there are several ways to get the first element of an array. The most common and efficient approaches include using bracket notation, the at() method, or destructuring assignment.
Using Bracket Notation (Most Common)
The simplest way is to access the element at index 0 using bracket notation:
let fruits = ["apple", "banana", "orange"]; let firstFruit = fruits[0]; console.log(firstFruit); // Handle empty arrays let emptyArray = []; let firstElement = emptyArray[0]; console.log(firstElement);
apple undefined
Using the at() Method
The at() method provides a modern alternative for accessing array elements:
let colors = ["red", "green", "blue"]; console.log(colors.at(0)); // First element console.log(colors.at(-1)); // Last element // With empty array let empty = []; console.log(empty.at(0));
red blue undefined
Using Destructuring Assignment
Destructuring allows you to extract the first element directly:
let numbers = [10, 20, 30]; let [first] = numbers; console.log(first); // With default value for empty arrays let emptyArray = []; let [firstWithDefault = "No element"] = emptyArray; console.log(firstWithDefault);
10 No element
Safe First Element Function
Here's a utility function to safely get the first element:
function getFirstElement(arr) {
return arr.length > 0 ? arr[0] : undefined;
}
let studentDetails = [
{ firstName: "John" },
{ firstName: "David" },
{ firstName: "Bob" }
];
let firstStudent = getFirstElement(studentDetails);
console.log(firstStudent ? firstStudent.firstName : "No students found");
// Test with empty array
let emptyStudents = [];
let firstEmpty = getFirstElement(emptyStudents);
console.log(firstEmpty ? firstEmpty.firstName : "No students found");
John No students found
Comparison
| Method | Empty Array Result | Browser Support | Use Case |
|---|---|---|---|
array[0] |
undefined |
All browsers | Most common, fastest |
array.at(0) |
undefined |
Modern browsers | Negative indexing support |
[first] = array |
undefined |
ES6+ | Multiple assignments |
Conclusion
For getting the first array element, use array[0] for simplicity and broad compatibility. The at() method offers additional features, while destructuring is useful when extracting multiple elements simultaneously.
Advertisements
