Thursday, October 23, 2025
HomeLanguagesJavascriptUnderscore.js _.nth() Method

Underscore.js _.nth() Method

The _.nth() method takes an array and an index and hence returns the element on that index in that array.

Syntax:

_.nth(array, index);

Parameters:

  • array: The given array from the element is taken.
  • index: The index on which an element is found.

Return Value: This method returns an element on the given index.

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

underscore.js contrib library can be installed using:

npm install underscore-contrib –save

Example 1: In this example, we will get an element from an array using this method.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [-1, -25, -43, 10, 125, -1];
// Getting nth element
let elem = _.nth(array, 2)
console.log("Original Array : ", array);
console.log("Element: ", elem);


Output:

Original Array :  [ -1, -25, -43, 10, 125, -1 ]
Element:  -43

Example 2: For out of bonds indexes, this method returns undefined.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [-1, -25, -43, 10, 125, -1];
// Getting nth element
let elem = _.nth(array, 100)
console.log("Original Array : ", array);
console.log("Element: ", elem);


Output:

Original Array :  [ -1, -25, -43, 10, 125, -1 ]
Element:  undefined

Example 3: For non-existing negative indexes, this method returns undefined.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [-1, -25, -43, 10, 125, -1];
// Getting nth element
let elem = _.nth(array, -1)
console.log("Original Array : ", array);
console.log("Element: ", elem);


Output:

Original Array :  [ -1, -25, -43, 10, 125, -1 ]
Element:  undefined
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen 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!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS