1

I wrote this solution to a problem I had, but I don't feel entirely comfortable with it. It seems to be dangerous, or at least in bad practice to use an array to redefine itself, sort of like trying to define a word but using the word in the definition. Can anyone explain either why this is wrong, or why it's ok?

let array = [] // other stuff happens to fill the array array = array.filter(element => element !== true) 

The reason I'm doing it this way is that I need that same variable name (array, for these purposes) to remain consistent throughout the function. The contents of the array might be added or removed multiple times before the array gets returned, depending on other behavior happening around it.

Let me know if this is too vague, I'll try to clarify. Thanks!

2
  • This is completely okay, you are filtering out values that are not true, and you aren't redifining the array on a completely other basis. Commented Aug 7, 2018 at 13:19
  • Using more descriptive intermediate names helps readability without having to add excessive comments, but other than that, if the intermediate result is not exposed to the outside, i don't see any issue. Commented Aug 7, 2018 at 13:19

2 Answers 2

1

It's perfectly fine. The right side (array.filter(element => element !== true)) of the assignment will be evaluated first, generate a completely new array and only then it'll be assigned back into array.

Sign up to request clarification or add additional context in comments.

1 Comment

This is great to know for future reference, thank you!
0

You can loop through your array backwards and remove the items, as to not allocate another array and reassign.

for (i = array.length - 1; i >= 0; --i) { if (!!array[i]) { array.splice(i, 1); } } 

This solution is:

  1. Fast
  2. Memory efficient
  3. Will not interfere with any other code that has a reference to your original array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.