DEV Community

Nedy Udombat
Nedy Udombat

Posted on • Updated on

Understanding JavaScript Array Series XVI - Array.push()

Let's assume you have a list of rappers like this J Cole, Kendrick Lamar, Chance The Rapper, Jay Z and you want to add one more rapper to that list, where would you add it? To the end of the list right? If you add Eminem to that list, you'll have J Cole, Kendrick Lamar, Chance The Rapper, Jay Z, Eminem.

We can achieve this behaviour using an array to store the names and an array method to add the new name to the list

const rappers = ['J cole', 'Kendrick Lamar', 'Chance The Rapper', 'Jay Z'];
const count = rappers.push('Eminem');
console.log(count) // 5
console.log(rappers); // ['J cole', 'Kendrick Lamar', 'Chance The Rapper', 'Jay Z', 'Eminem']

I was able to achieve this by using the Array.push() method. This method adds new items to the end of the array and returns the new length of the array. Just like in the example above, the result of rappers.push('Eminem') was returned into the count variable which logs 5.The rappers variable is also updated with the new item.

Let's take a look at the syntax:

arr.push(item1, item2, item3, ..., itemN);

[item1, item2, item3, ..., itemN]: These are the elements to be added to the array.

What happens When no new item is provided and the .push method is called on an array?

const rappers = ['J cole', 'Kendrick Lamar', 'Chance The Rapper', 'Jay Z'];
const count = rappers.push();
console.log(count); // 4
console.log(rappers); // ['J cole', 'Kendrick Lamar', 'Chance The Rapper', 'Jay Z']

In this scenario, nothing happens and the original length of the array is returned.

That's all for today, See you next week!!! 😆 😁

Here is the link to the other articles on this Array series written by me:

Got any question, addition or correction? Please leave a comment.

Thank you for reading. 👍

Top comments (1)

Collapse
 
slimzycm profile image
Slimzy.CM

Nice post boss