Top 5 JavaScript Methods You Should Know

JavaScript arrays are one of the most powerful and versatile data structures in web development. They allow us to store and manipulate collections of data in a variety of ways. This blog post will teach you the most important JavaScript array methods, including push(), pop(), unshift(), shift(), unshift(), indexOf(), splice(), slice(), join(), and reduce(). By learning these methods, you can write more efficient and powerful code. 

1. push() By utilizing the push() method, you can effortlessly append an element to the end of an array, like in the instance below where "banana" is added to the fruits array's end:

fruits = ['apple', 'orange', 'pear'];
fruits.push('banana');
console.log(fruits);
// Output ['apple', 'orange', 'pear', 'banana']

2. pop() By utilizing the pop() method, the last item within an array can be extracted and deleted, with its value being returned. For instance, take the following code where the last element of the fruits array is removed and stored within the lastFruit variable:

fruits = ['apple', 'orange', 'pear'];
lastFruit = fruits.pop();
console.log(lastFruit); // Output: pear
console.log(fruits); // Output: ['apple', 'orange']

3. unshift() The unshift() method adds an element to the beginning of an array. For example, the following code would add the element "banana" to the beginning of the array fruits:

fruits = ['apple', 'orange', 'pear'];
fruits.unshift('banana');
console.log(fruits);
// Output ['banaba', 'apple', 'orange', 'pear']

4. shift() The shift() method removes the first element from an array and returns it. For example, the following code would remove the first element from the array fruits and store it in the variable firstFruit:

fruits = ['apple', 'orange', 'pear']; 
firstFruit = fruits.shift(); console.log(firstFruit); // Output: apple
console.log(fruits); // Output: ['orange', 'pear']

5. indexOf() The indexOf() method returns the first index at which a given element can be found in an array, or -1 if it is not present.

const fruits = ['apple', 'banana', 'orange'];
const orangeIndex = fruits.indexOf('orange');
console.log(orangeIndex); // Output: 2

Related Blogs

How To Play m3u8 File in HTML Video Player Using JavaScript

Contact

Saif Ur Rehman

I am always available for freelance work. Connect with me via and call in to my account.

Chat with us 👋