Syntax, Parameter, and Return Value
Syntax:
_.first(array)
Parameters:
array (Array): The array to query.
Return Value:
The first element of array.
Examples
Basic Usage:
Retrieving the first element from an array.
JavaScript
let numbers = [1, 2, 3, 4, 5];
let firstNumber = _.first(numbers);
console.log(firstNumber);

You can also try this code with Online Javascript Compiler
Run Code
Output:
1
Array of Objects:
Getting the first object from an array of objects.
JavaScript
let users = [{ name: 'Alice' }, { name: 'Bob' }, { name: 'Carol' }];
let firstUser = _.first(users);
console.log(firstUser);

You can also try this code with Online Javascript Compiler
Run Code
Output:
{ name: 'Alice' }
Empty Array:
Handling an empty array.
JavaScript
let emptyArray = [];
let firstElement = _.first(emptyArray);
console.log(firstElement);

You can also try this code with Online Javascript Compiler
Run Code
Output:
undefined
Combined with Other Lodash Methods:
Using _.first() in combination with other Lodash methods.
JavaScript
let numbers = [1, 2, 3, 4, 5];
let doubledFirst = _.chain(numbers).map(n => n * 2).first().value();
console.log(doubledFirst);

You can also try this code with Online Javascript Compiler
Run Code
Output:
2
Frequently Asked Questions
What does _.first() return for an empty array?
For an empty array, _.first() returns undefined, as there is no element to retrieve.
Is there a difference between _.first() and _.head()?
No, _.first() and _.head() are aliases in Lodash and function identically.
Can _.first() be used with arrays of any type?
Yes, it works with arrays of any type, including objects, strings, and numbers.
Conclusion
The Lodash _.first() method offers a straightforward and efficient way to access the first element of an array. Its simplicity and utility in scenarios where only the initial element is required make it a valuable tool in a developer's toolkit. This method enhances the readability and maintainability of code, especially in data retrieval and user interface operations.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.