Open In App
Related Articles

Lodash _.head() Method

Improve Article
Improve
Save Article
Save
Like Article
Like

Lodash _.head() method is used to get the first element of an array.

Syntax

_.head( array );

Parameters:

  • array: This parameter holds the query array.

Return Value:

It returns the first element of the array.

Example 1: In this example, we are getting the first element of the given array by the use of the _.head() method.

javascript




const _ = require('lodash');
 
let ar = [1, 2, 3, 4, 5]
let first = _.head(ar);
 
console.log(first)


Output:

1

Example 2: In this example, we are getting the first element of the given array of objects by the use of the _.head() method.

javascript




const _ = require('lodash');
 
let ar = [{ a: 1, b: 2 }, { c: 3, d: 4 }, { e: 5, f: 6 }]
let first = _.head(ar);
 
console.log(first)


Output:

{ a: 1, b: 2 }

Example 3: In this example, we are getting undefined as the given arrray is empty.

javascript




const _ = require('lodash');
 
let ar = []
let first = _.head(ar);
 
console.log(first)


Output:

undefined 

Note: This will not work in normal JavaScript because it requires the library lodash to be installed.

Reference: https://lodash.com/docs/4.17.15#head


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 03 Nov, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials