Syntax, Parameter and Return Value
Syntax:
_.head(array)
Parameters:
array (Array): The array to query.
Return Value:
Returns the first element of array.
Examples
Basic Example:
JavaScript
var _ = require('lodash');
var array = [1, 2, 3, 4, 5];
var firstElement = _.head(array);
console.log(firstElement);

You can also try this code with Online Javascript Compiler
Run Code
Output:
1
A simple demonstration of retrieving the first element from an array.
Working with Strings:
JavaScript
var stringArray = ['Hello', 'World', 'JavaScript'];
var firstString = _.head(stringArray);
console.log(firstString); ‘

You can also try this code with Online Javascript Compiler
Run Code
Output:
'Hello'
_.head() can also be used to get the first string from an array of strings.
Arrays of Objects:
JavaScript
var objectArray = [{ id: 1 }, { id: 2 }, { id: 3 }];
var firstObject = _.head(objectArray);
console.log(firstObject);

You can also try this code with Online Javascript Compiler
Run Code
Output:
{ id: 1 }
An example showing how _.head() can retrieve the first object from an array of objects.
Empty Array Handling:
JavaScript
var emptyArray = [];
var result = _.head(emptyArray);
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output:
undefined
Demonstrates that _.head() returns undefined when used on an empty array.
Frequently Asked Questions
How does _.head() differ from using array indexing?
_.head() is a more readable alternative to array[0], especially in functional programming patterns, emphasizing code clarity and simplicity.
What happens if _.head() is used on a non-array?
If used on a non-array or an invalid input, _.head() returns undefined, highlighting the importance of input validation.
Can _.head() work with array-like objects?
Yes, it can retrieve the first element from array-like objects, such as arguments or NodeList objects.
Conclusion
The _.head() method in Lodash offers an elegant and readable way to access the first element of an array. Its simplicity makes it a preferred choice over traditional array indexing in many cases, enhancing code readability and efficiency. Understanding and utilizing _.head() is a step towards more elegant and cleaner code in JavaScript.
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.