JavaScript's nthElement Function

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will dive into the nthElement function in JavaScript which returns the nth element of an array. You will learn how to use Array.prototype.slice() to extract an element from an array, and how to handle out-of-bound indices gracefully. By the end of this lab, you will have a solid understanding of the nthElement function and how it can be useful in your JavaScript projects.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28513{{"`JavaScript's nthElement Function`"}} javascript/data_types -.-> lab-28513{{"`JavaScript's nthElement Function`"}} javascript/arith_ops -.-> lab-28513{{"`JavaScript's nthElement Function`"}} javascript/comp_ops -.-> lab-28513{{"`JavaScript's nthElement Function`"}} end

Finding the NTH Element of an Array

To find the nth element of an array, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Array.prototype.slice() to create a new array containing the nth element.
  3. If the index is out of bounds, return undefined.
  4. Omit the second argument, n, to get the first element of the array.

Here's an example code that implements this:

const nthElement = (arr, n = 0) =>
  (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];

You can test this function with the following examples:

nthElement(["a", "b", "c"], 1); // Output: 'b'
nthElement(["a", "b", "b"], -3); // Output: 'a'

By following these steps, you can easily find the nth element of an array using JavaScript.

Summary

Congratulations! You have completed the NTH Element lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like