Include multiple conditions in an if statement without repeating

Viewed 74

I am trying to write it so that the if statement executes if it is not null and not "". I know I can just do && then copy the same thing over and change the null to "" but is there a way to do something like:

!= null && ""

original if statement:

if(msg['component']['section']['entry']['code']['@code'].toString() != null)
3 Answers

Well you could use a dummy variable to hold the value:

var value = msg['component']['section']['entry']['code']['@code'].toString();
if (value != null && value != "") {
    // some logic here...
}

However, JavaScript supports the concepts of "truthy" or "falsy." In this case, you might just be able to accept the following:

if (msg['component']['section']['entry']['code']['@code'].toString()) {
    // logic
}

you could do a exclamation mark that will be true for null and an empty string

if(!msg['component']['section']['entry']['code']['@code'])

You can use optional chaining in every place where null value can appear, you don't have to call it by ['...'] (unless object key is non-alphanumeric, like your @code), e.g. let's assume that every property in chain might be a null (bad practice, but sometimes can happen):

if (
 msg?.component?.section?.entry?.code?.['@code']?.toString()
)

Above code will return false if any property in chain will be null (in fact falsy, but as I can see those all in chain needs to be objects, otherwise it wouldn't be any sens in it).

Here you have all falsy values in JavaScript.

Usually you need to be careful for 0, but in your case, you are doing toString(), so you are fine with this.

Alternate solution

If you have a lot of values and you want to check if any or every of them match condition, you can also use Array.property.some or Array.property.every. e.g. :

const randomArray = [{ x: 5 }, '', null, {y: 5}, 0]

// "!!" will cast "falsy" to "false" and any other to "true"
if (randomArray.every(e => !!e)) { 
  console.log('All items are not falsy')
}

if (randomArray.some(e => !e)) {
  console.log('There is at least 1 falsy element')
}

if (randomArray.some(e => e !== '' || e !== null)) { 
  console.log('There is at least 1 empty string or null')
}

Related