JavaScript : How to returns the element of that index

Java Script @ Freshers.in

JavaScript Arrays are a fundamental data structure that allows developers to store and manipulate collections of data efficiently. One of the lesser-known but powerful methods provided by JavaScript arrays is the at() method. In this tutorial, we will explore the at() method in detail. Through practical examples and clear explanations, you will learn how to effectively leverage this method in your JavaScript projects.

Understanding the at() Method

The at() method is an innovative addition to the Array prototype introduced in ECMAScript 2021 (ES12). It enables you to access elements within an array based on their index, similar to using the traditional square bracket notation. However, the significant advantage of the at() method lies in its ability to handle negative indices and return undefined instead of throwing an “Index Out Of Range” error. This feature can be especially useful when working with arrays containing elements with unique identifiers, such as those starting with “freshers_in.”

Syntax

The syntax for the at() method is straightforward:

array.at(index)

Parameters

index (required): The index of the element to retrieve from the array. It can be a positive or negative integer.

To demonstrate the capabilities of the at() method, let’s create an example :

const jobApplicants = [
  "freshers_in_JS",
  "freshers_in_WebDev",
  "experienced_in_JS",
  "freshers_in_DataScience",
  "experienced_in_WebDev"
];

Example 1: Accessing Elements with Positive Indices

We can use the at() method to access elements by providing positive indices:

const firstFreshersJob = jobApplicants.at(0);
console.log(firstFreshersJob); // Output: "freshers_in_JS"

Example 2: Accessing Elements with Negative Indices

The at() method allows us to access elements using negative indices as well:

const lastFreshersJob = jobApplicants.at(-2);
console.log(lastFreshersJob); // Output: "freshers_in_DataScience"

Example 3: Handling Out-of-Range Indices

Unlike conventional array access, the at() method handles out-of-range indices gracefully:

const nonExistentJob = jobApplicants.at(10);
console.log(nonExistentJob); // Output: undefined

Example 4: Using at() in a Loop

The at() method can be helpful in looping through specific elements of an array:

for (let i = 0; i < jobApplicants.length; i++) {
  if (jobApplicants[i].startsWith("freshers_in")) {
    console.log(jobApplicants.at(i));
  }
}

Get more articles on Java Script

Author: user

Leave a Reply