DEV Community

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

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan
const array = ['🦊'];

array.push('🐴');
array.splice(array.length, 0, '🐴');
array[array.length] = '🐴';

// Result
// ['🦊', '🐴']

What's the point of these two lines?

array.splice(array.length, 0, '🐴');
array[array.length] = '🐴';

Pretty sure array.push('🐴'); already gets the job done.

Collapse
 
luisaugusto profile image
Luis Augusto • Edited

I think it is just showing that there are three ways to make a mutative change to an array, each line does the same thing.

array.push('🐴') simply adds to the end of the array
array.splice(array.length, 0, '🐴') removes 0 items from the end of the array, and adds one item
array[array.length] = '🐴' adds an item to a specific position, which in this case is at the end of the array

Collapse
 
samanthaming profile image
Samantha Ming

yes, that's what I'm trying to do, thanks for clarifying Luis!

Aleksandr, I see how's that can be confusing...maybe i should fix it up πŸ€”

Thread Thread
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

Ah, yep, I thought it was all being executed sequentially