Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make this large if-statement more readable in JavaScript

Tags:

javascript

I need to make the following large if-statement more readable in JavaScript.

Any ideas?

if ( Tools.Array.contains( that.pAutocompleteAliasUsed[i], this.currentString) !== false  &&
    ( this.autocomplete.list.length === 0 ) || ( this.currentString.toLowerCase() !== this.autocomplete.list[0].target.alias.toLowerCase() ) )
{
    make something
}
like image 233
antonjs Avatar asked Jul 01 '26 02:07

antonjs


2 Answers

One thing you can do to make things more readable is to extract the various logical tests out of the if statement. It is much easier to read a single statement and then nicely named boolean parameters in the if test.

I have done this for the first test in this example, I have had a go with the other others, but you could name them better than me as you know what they are testing.

var toolsContainsString = Tools.Array.contains(that.pAutocompleteAliasUsed[i], this.currentString) !== false;
var isAutoCompleteEmpty = this.autocomplete.list.length === 0;
var isTargetMatch = this.currentString.toLowerCase() !== this.autocomplete.list[0].target.alias.toLowerCase();

if (toolsContainsString && (isAutoCompleteEmpty || isTargetMatch)) {
    //make something
}
like image 132
Fenton Avatar answered Jul 03 '26 16:07

Fenton


 if( Tools.Array.contains( that.pAutocompleteAliasUsed[i], this.currentString) !== false  &&
        ( this.autocomplete.list.length === 0 ) || 
        ( this.currentString.toLowerCase() !== this.autocomplete.list[0].target.alias.toLowerCase() )
   )
 {
          // something
 }
like image 38
Saboor Awan Avatar answered Jul 03 '26 14:07

Saboor Awan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!