Open In App

Lodash _.head() Method

Last Updated : 03 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads