DEV Community

Jaisurya
Jaisurya

Posted on

JavaScript Array Methods

JavaScript has its own set of methods built into the language that allow developers to efficiently interact with arrays. JavaScript allows us to do such operations as adding, removing, updating or getting elements, transforming, or iterating through arrays.

Array Basic Methods

1. Array toString() in JavaScript

This method fabricates an array in a string format separated by a comma. This approach does not alter the initial array and is significant for representing the content of the array in the form of a string.

Example code:

const names = ["Jaisurya", "Dinesh", "Ramesh"];
console.log("Arrays to String is", names.toString());
//Output: Array to String is Jaisurya, Dinesh, Ramesh

Enter fullscreen mode Exit fullscreen mode

Explanation:

In the above example, we defined a variable named names using the const keyword. We assigned it an array consisting of names. We utilized the toString() method to transform the array into a single string and logged the result in the console.

2.Array at() in JavaScript

It returns the element at a specified index in an array. It can be constructed for both positive and negative indices. Indices can be positive, which begin at the start ( 0-based ), and can be negative, which count from the end of the array.

Example code:

const names = ["Jaisurya", "Ramesh", "Dinesh"];
console.log("Second Element is", names.at(1));//Access second element
console.log("Last Element is", names.at(-1));//Access last element

//Output:
//Second Element is Ramesh
//Last Element is Dinesh

Enter fullscreen mode Exit fullscreen mode

Explanation:

In the above example, we defined a variable named names using the const keyword and assigned it an array consisting of names. By utilizing the at() method of array, we accessed the second and last element from the array and logged them in the console.

3.Array forEach() in JavaScript

The forEach() method is a built-in method that is utilized to call a function for each element present in the array. It neither returns a new array nor modifies the original array, but it is utilized for iteration.

Example code:

const seasons = ["spring", "summer", "winter", "autumn"];

seasons.forEach((season) => console.log(season));

//Output:
//spring
//summer
//winter
//autumn

Enter fullscreen mode Exit fullscreen mode

Explanation:

In the above code, we defined a variable named season and assigned it an array consisting of season names. By utilizing the forEach() method, we return every element of the array and log the output in the console.

Top comments (1)

Collapse
 
alexcodebytes profile image
Oleksandr

Great refresher on array methods! Knowing how to properly iterate, transform, and handle arrays without mutating the original data is fundamental for writing clean and robust JavaScript code. Thanks for putting this guide together!