Reputation: 41
I'm looking at some legacy code from another developer and I see this mysterious line:
if (hasEmail) {
fields.push();
}
Very confused... I think this line doesn't do anything because the push has no elements being pushed, but before I delete it, I want to know if there is something I don't know, some javascript usage of push I had never considered.
Upvotes: 1
Views: 204
Reputation: 371069
If that's all the code is, yes, it doesn't do anything.
const arr = [];
arr.push();
console.log(arr);
Every element passed to push
is added to the end of the array. If no elements are passed, no elements are added. But, there's one more thing to consider - push
returns the new length of the array. So it would be theoretically possible (though quite unlikely in a sane codebase) to see something like
const arr = ['foo', 'bar'];
console.log(arr.push() * arr.push());
where the push
is used to get to get the length of the array, so make sure the expression isn't being used before deleting it.
Although the first argument isn't shown as optional on MDN, the spec shows that the first argument is indeed optional:
https://tc39.github.io/ecma262/#sec-array.prototype.push
- Let O be ? ToObject(this value).
- Let len be ? ToLength(? Get(O, "length")).
- Let items be a List whose elements are, in left to right order, the arguments that were passed to this function invocation.
- Let argCount be the number of elements in items.
- If len + argCount > 253-1, throw a TypeError exception.
- Repeat, while items is not empty
a. Remove the first element from items and let E be the value of the element.
b. Perform ? Set(O, ! ToString(len), E, true).
c. Let len be len+1.
- Perform ? Set(O, "length", len, true).
- Return len.
When nothing is passed, step 6 just doesn't repeat at all.
Upvotes: 2