Files
30-seconds-of-code/snippets/nth-arg.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

535 B

title, tags, cover, firstSeen, lastUpdated
title tags cover firstSeen lastUpdated
Nth argument function mug-flower-book 2018-01-23T21:27:37+02:00 2020-10-21T21:54:53+03:00

Creates a function that gets the argument at index n.

  • Use Array.prototype.slice() to get the desired argument at index n.
  • If n is negative, the nth argument from the end is returned.
const nthArg = n => (...args) => args.slice(n)[0];
const third = nthArg(2);
third(1, 2, 3); // 3
third(1, 2); // undefined
const last = nthArg(-1);
last(1, 2, 3, 4, 5); // 5