Search code examples
javascriptarraysdeclarationsquare-bracket

Is it bad to use a "not declared array"? Does the "not declared" array have a proper name in programming?


I was trying to use a if...else statement with arrays without having to declare the arrays. I got it to work this way:

if(['banana','apple','lemon'].indexOf(somevar) >-1)
{
 //code
}
else if(['chicken','dog','elephant'].indexOf(somevar) >-1)
{
 //code
}
.
.
.

And it keep going this way until some dozens of if...elses. The code is working fine, no problem noticed. Is it a bad pratice? Is it really an array? Can it cause some performance loss, memory leaks, or reference problems? Does the "not declared" array used in this code, if it is really an array, have a proper name in programming?


Solution

  • It seems pointless in my opinion, since you know exactly what element you want.

    As for memory, the array should be deallocated as soon as you move to the next statement, and I would personally consider this bad practice in this instance, since, like I said earlier, it doesn't do anything since you know which will be selected.

    If it's a static list that the user is going to select an element from, this is alright but I would probably define the array elsewhere and just reference that when needed, so you don't have to create the exact same array over and over again.

    I consider it bad practice since if I wanted to add/remove/change an element in an array, I would rather just change the array when it's declared at the top, or change the data source. By sprinkling it through your code, you allow the possibility of hard to maintain code.