Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Foundations Arrays Getting and Setting

Jason Nelson
Jason Nelson
9,127 Points

my_array[my_array.length] = "abc"

to add a new item to the array, couldn't you also do my_array.push("abc");

3 Answers

Ruben Leija
Ruben Leija
4,051 Points

Yes you can. Using the push function does not allow you to add custom keys to the value your pushing. The other way does.

Examples:

z = [1,3,4];

z.push(0);

// Returns z = [ 1, 3, 4, 0] No key but defaults

z = [];

z['hello'] = 'world';

// Returns z = [ { 'hello' : 'world' } ] The value world has a key of hello to be reference

Let me know if that make sense

Stone Preston
Stone Preston
42,016 Points

yes, both those ways add a new element to the end of the array. however the difference is that using push also returns the new length of the array in addition to adding the new element. You can also add more than one element at a time using push