DEV Community

loading...

7 Essential Array Methods In JavaScript (2021)

Jatin Kumar
Learning new tech everyday
・2 min read

Looking for the easiest way to add, remove or find elements from an array? After reading this article you'll be able to do basic JS operations related to an array in just one line. Each method is explained with a code example.

Overall there are several methods available in the JavaScript ecosystem. This article will cover the basic 7 methods through which you will be able to add, remove or find elements from an array in no time.

Let's get started by assuming five vegetable emojis in an array.

Initial state of vegetables array

PUSH

The push method adds an element to the last position of an array.

push method

The push() can be used with apply() to merge arrays.

merge two or more arrays with push method using apply from Array.prototype

UNSHIFT

The unshift method adds an element to the first position of an array.

add elements using unshift method

The unshift() can be used to add a nested array at the beginning of an array.

unshift method

POP

The pop method removes the last element from an array.

pop method

Using pop() method on an empty array will returns undefined

CONCAT

The concat method can merge multiple arrays and returns a single combined array.

concat method

The conact() can be used to merge any type of object in an array.

SHIFT

The shift method removes the first element from an array.

shift method

The shift() can be used to iterate through the array while printing the results.

Iterate over an array and remove all the elements using the shift method

INDEXOF

The indexOf method returns the first position of an element which can be found in an array.

indexOf method

This IndexOf() can be used to find occurrences of an element in an array.

indexOf method

LASTINDEXOF

The lastIndexOf method returns the last position of an element which can be found in an array.

lastIndexOfcode method

This lastIndexOf() can be used to find occurrences of an element in an array.

find occurances using lastIndexOf method

Now, you'll be able to perform basic operations using array methods. 😎


Sign up for the Medium newsletter to get notified about the next blog JavaScript posts and possible future giveaways

Medium Newsletter

Twitter

LinkedIn


Happy coding!


Discussion (0)