Home > Software engineering >  Javascript - compare item to null if it exists
Javascript - compare item to null if it exists

Time:03-24

I have a dropdown list that can be used for different data. Sometimes the data has an isActive flag (a BOOLEAN) and sometimes it does not. If it does not have the flag at all, I want to display the dropdown item in black. If it does, I want to check the isActive flag and if true, display the item in black, otherwise display it in red. In the following statement, the text.danger class means "red".

<tr *ngFor="let item of resultItems; let i = index;" [class.active]="activeRowIndex === i" [class.text-danger]="!item?.isActive ? false : (item.isActive === null ? true : false)"

When the isActive flag is not present, it does the right thing and shows the items in black. When the flag does exists, the items are ALWYAS displayed in black. What is my problem?

CodePudding user response:

If it doesn't exist, it will be undefined, not null. When you use the === operator with null, it will only accept null and no other value. If you use == however, it will accept both null and undefined.

That said, your code still doesn't follow what you want it to do. Your first check (!item?.isActive) will be true when isActive is false, which means the whole expression becomes false and the text will be black. Also, undefined and null are "falsy", so if you have one of those it will never come into the other sub-expression (item.isActive === null ? true : false)

I'd start with checking for null/undefined, and if it isn't undefined/null, look at the value. Like this:

item?.isActive == null ? false : !item?.isActive 

This can even be simplified to:

item?.isActive != null && !item?.isActive

CodePudding user response:

Just to clear the problem. For example:

interface Intf {
  isActive?: boolean;
};


const first: Intf = {
  isActive: true
};

const second: Intf = {
 isActive: false
};

const third: Intf = {};


console.log(first?.isActive ? true : false); // true
console.log(second?.isActive ? true : false); // false
console.log(third?.isActive ? true : false); // false

If you're using the '?' operator, there's no need for additional checking. If the active it's there then you're checking his value. If not, that's 'false' from the beginning

  • Related