Thursday, January 9, 2025
Google search engine
HomeLanguagesJavascriptLodash _.head() Method

Lodash _.head() Method

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

Syntax

_.head( array )

Parameters: This method accepts single parameter as mentioned above and described below:

  • array: This parameter holds the query array.

Return Value: It returns the first element of the array.

Example 1:




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


Output:

1

Example 2:




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:




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


Output:

undefined

Note: The _.head() method on an empty array returns 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

RELATED ARTICLES

Most Popular

Recent Comments