Head of array

OSCC · JavaScript, Array · Oct 19, 2020

Returns the head of an array.

  • Check if arr is truthy and has a length property.
  • Use arr[0] if possible to return the first element, otherwise return undefined.
const head = arr => (arr && arr.length ? arr[0] : undefined);
head([1, 2, 3]); // 1
head([]); // undefined
head(null); // undefined
head(undefined); // undefined

Recommended snippets & collections

  • JavaScript Array Tricks

    Snippet collection

    Learn a handful of awesome tips and tricks that you can leverage in your code to make array manipulation a breeze.

  • Creates an array of elements, ungrouping the elements in an array produced by zip and applying the provided function.

  • Mutates the original array to filter out the values specified, based on a given iterator function.

  • JSON to CSV

    JavaScript, Array

    Converts an array of objects to a comma-separated values (CSV) string that contains only the columns specified.