Thursday, July 4, 2024
HomeLanguagesJavascriptJavascript Array at() Method

Javascript Array at() Method

The JavaScript Array at() method takes an integer value (index) as a parameter and returns the element of that index. It allows positive and negative integers. For the negative integer, it counts back from the last element in the array.

Syntax:

at(index);

Parameter: This method accepts one parameter that are described below:

  • index: This parameter specifies the array index of the element. The negative index value counts back from the end of array.

Return Value: The element corresponding to the specified index in the array. It returns undefined value if we access index < 0, or index + array.length.

Example 1: This code shows the value extracted at the given index.

Javascript




const arr = [45, 32, 69, 21];
const index = 3;
 
console.log(arr.at(index));


Output

21

Example 2: It will provide a function that returns the last element found in a specified array.

Javascript




const subjects = ["Maths", "Physics", "Biology", "Chemistry"];
 
function lastElement(arr) {
    return arr.at(-1);
}
 
const item = lastElement(subjects);
console.log(item);
 
subjects.push("DSA");
const item2 = lastElement(subjects);
console.log(item2);


Output

Chemistry
DSA

Supported Browsers:

  • Google Chrome 92
  • Edge 92
  • Firefox 90
  • Opera 78
  • Safari 15.4
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!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments