DEV Community

Parth Chokshi
Parth Chokshi

Posted on

Initialize a const variable inside a function getting called simultaneously

What is the good practice to initialize a variable inside a function that is getting called simultaneously like a call back function for search?

I have a function for search right now which is getting called with every key press in React. Is it good to do:

constructor() {
    this.searchResults = []
}


searchResult  = term => {
    this.searchResults = this.array.filter(arr => term == arr.something)
    this.setState({ searchResults: this.searchResults })
}

OR

searchResult  = term => {
    const searchResults = this.array.filter(arr => term == arr.something)
    this.setState({ searchResults })
}

Will the const variable get garbage collected after each keypress?

Top comments (3)

Collapse
 
nektro profile image
Meghan (she/her)

the second is better because the first will have to get re-allocated after every call and will never disappear. whereas in the second, you use constant variables, which is a good pattern, but also the fact that it is local to the block of the arrow function, the GC can automatically know to de-allocate searchResults after the end of all searchResult(term) calls.

Collapse
 
dylanesque profile image
Michael Caveney

Agreed, plus the second one reads a little bit cleaner.

Collapse
 
parthchokshi profile image
Parth Chokshi

Ah! Yes, if it is outside function, it will remain there even after the function execution and won't be deallocated. Makes sense. Thanks.