Search code examples
angulartypescriptforeachngrx

Are there any better way to remove this typescript code if check?


I am going to iterate object array called a.but a can be undefined also.so, I use the 'if' check before iterating the array. but need to know is there any better way to do it?

let a =  //a can be undefined or set of obejct
if (a !== undefined) {
  a.forEach(value => {
    console.log(value);
  });
}

I tried using a?.foreach but then given the sonar issue as Expected assingment or functional called .In above way given me complexity issues.


Solution

  • You're quite correct that you can use the optional chaining operator for this:

    a?.forEach(value => {
        console.log(value);
    });
    

    If Sonar is giving you an error for that, it may be that it's out of date and doesn't understand the optional chaining operator, which is fairly new. You might be able to upgrade it, or tell it to ignore this line of code.

    You can also just use if (a) rather than if (a !== undefined):

    if (a) {
        a.forEach(value => {
            console.log(value);
        });
    }