Improve condition code

I have the following code

var oDataEn = aData[0][aProperties[0].split('/')[0]]; if (!(oDataEn != null && oDataEn.results && oDataEn.results.length > 0)) { ... else ... 

This works OK , unless

 aData[0] = 'undefined' 

my question is is there a better way to write and not add up

  if(aData[0] != null) { var oDataEn = aData[0][aProperties[0].split('/')[0]]; } 

I do not want to have two, if possible ...

+4
source share
3 answers

Start with a ternary point - I assume that aData [0] could be false (null, undefined, 0 or ""):

 var oDataEn = aData[0]?aData[0][aProperties[0].split('/')[0]]:null; if (oDataEn && oDataEn.results && oDataEn.results.length > 0) { 
+8
source
  if(aData[0] === undefined){} 

is the best way, as far as I know.

According to your comment

  if(typeof aData[0] != 'undefined' /*&& other if statements*/){} 

Therefore, it will not be processed if it is undefined.

0
source

Using the ternary operator u, we can do this. The ternary operator will reduce only the line of codes.

  var oDataEn = aData[0] === undefined ? '' : aData[0][aProperties[0].split('/')[0]]; 
0
source

Source: https://habr.com/ru/post/1246045/


All Articles