DEV Community

Nedy Udombat
Nedy Udombat

Posted on β€’ Edited on

3 1

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. πŸ‘

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (1)

Collapse
 
slimzycm profile image
Slimzy.CM β€’

Nice post boss

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay