Magus
Magus

Reputation: 15124

array.splice vs setting a value to null

You should use array.splice(i, 1); instead of array[i] = null This will preserve the keys in the array

Source : Should I bother cleaning array in node.js?

I don't really understand this sentence. Why array[i] = null will change the keys of the array ? Why array.splice(i, 1); is better ?

Upvotes: 4

Views: 3040

Answers (2)

Tushar
Tushar

Reputation: 87233

array.splice(i, 1); will remove the element from array, so changing the length of array.

Whereas array[i] = null will just set the value at the index i to null and will not alter the array length. This is same as delete array[i] except the delete operator will set the value at the index to undefined.

Regarding

Why array[i] = null will change the keys of the array?

I think there is missing a word not in between the will and change.

So, according to me, it should be

Why array[i] = null will not change the keys(or rather length) of the array?

Second question:

Why array.splice(i, 1); is better?

It alters the length of the array by removing the element from it. So, when iterating over array you don't have to check if(value == null).

Which one to use totally depends on the use-case.

Upvotes: 5

James Brierley
James Brierley

Reputation: 4670

It's fairly easy to see the differences in behaviour with a simple test case. This is what Chrome outputs from the console:

var test = ['a','b','c']
test[1] = null
["a", null, "c"]

var test = ['a','b','c']
test.splice(1, 1)
["a", "c"]

var test = ['a','b','c']
delete test[1]
["a", undefined × 1, "c"]

As you can see, splice is the only one to change the index of c from 2 to 1.

Which one you want to use depends on your use case. There may be a case where you have a fixed-length array, and you want to remove an item without affecting the index of items after it, in which case splicing would be inappropriate.

Upvotes: 0

Related Questions