Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

.pop

When typing this array in the console :

var nums = [1, 2, 3, 4, 5, 6];

and you type nums.pop();

you get a return value of 6. But since the length of the array is now 5, shouldn't it say 5?

For example, when you do nums.push(7); it returns the number 7 (because there are now 7 items in the array).

What's the difference?

2 Answers

Steven Parker
Steven Parker
216,083 Points

The return value of a "pop" is not the number of items left in the array — it's the value of the item that it removes from the array. So in this example, it removes the value "6" from the end of the list.

On the other hand, "push" does return the number of items in the array.

Blake Larson
Blake Larson
12,988 Points

Pop() removes the last index of an array and returns the removed item. If it was [1,2,3,4,5,9] it would return 9 and nums is now [1,2,3,4,5].

If you do it to nums again like: let lastNum = nums.pop();

console.log(lastNum); 5 console.log(nums.length); 4