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?
Asked
Active
Viewed 807 times
2
-
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 Answers
7
Some differences:
popreturns the value of the entry that you're removing, assigning tolengthdoesn't.popis a method call; assigning tolengthis an assignment operation.popon an array whose length is0returnsundefinedand doesn't change the array.array.length -= 1on an array with alengthof0causes an error.
T.J. Crowder
- 959,406
- 173
- 1,780
- 1,769
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 ...
Jonas Wilms
- 120,546
- 16
- 121
- 140