3

I know that array is some kind of an object, but it also has numeric indexes. And arr.length is a property, which returns not the number of elements in the array, but the last index+1. We can remove the last element using decrement of length or function pop(). And the question is: What's the difference between these methods?

jpyams
  • 4,030
  • 9
  • 41
  • 66
GigaGeek
  • 196
  • 1
  • 10
  • you get the item with `pop`...? what is the changing of length for? – Nina Scholz Jul 06 '19 at 16:57
  • 1
    [Is it an antipattern to set an array length in JavaScript?](https://stackoverflow.com/questions/31547315) and [Javascript array length modification implications](https://stackoverflow.com/questions/43712345) – adiga Jul 06 '19 at 17:00

2 Answers2

8

Some differences:

  • pop returns the value of the entry that you're removing, assigning to length doesn't.

  • pop is a method call; assigning to length is an assignment operation.

  • pop on an array whose length is 0 returns undefined and doesn't change the array. array.length -= 1 on an array with a length of 0 causes an error.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
3

.pop() also returns the last element (which is often wanted):

const last = array.pop();
// vs
const last = array[array.length - 1];
array.length -= 1;

Now you can decide yourself which one of the above is more readable ...

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151