DEV Community

Discussion on: 5 Way to Append Item to Array in JavaScript

Collapse
 
stojakovic99 profile image
Nikola Stojaković

Great article!

Something for beginners (I'm pretty sure you already knew about this):

One hacky way to add an empty item to an array (if we can even call it appending an item to an array, I think more appropriate term would be resizing) would be:

const array = [1, 2];

array.length = 3;

console.log(array); // [1, 2, <1 empty item>]

However you should never ever do this.

Collapse
 
samanthaming profile image
Samantha Ming

Yes! Good one, let me add it to my notes 💪 Thanks for sharing 😀

Collapse
 
devhammed profile image
Hammed Oyedele

You can also use it to shrink array

const array = [1, 2]

array.length = 1

console.log(array) // [1]
Thread Thread
 
samanthaming profile image
Samantha Ming

WOOO! never thought of that! Adding to my notes!!! thanks for sharing 😁