0

How can I avoid repeating single variable inside an if to compare it with mutiple variables or, for example how can I avoid repeating mutation.type

const targetNode = documents.getElementsByClassName("container");
const = {attributes : true , childList : true , subtree : true};

const callback = (mutation,observer)=>{
   for(const mutation of mutationList){
      if(mutation.type === 'childList' || mutation.type === 'subtree' && mutation.type === 'attributes'){
//doing something 
}
}
}

I don't wanna repeat mutation.type all the time inside an if , not only in this case but also for further coding

IhateReact
  • 43
  • 6
  • 1
    may be destructure it initially `let { type } = mutation `, then use `["childList", "subtree", "attrubutes"].includes(type)` – joy08 Aug 16 '21 at 11:31

2 Answers2

2

You can declare a const to hold the types you want and check it against mutation.type

const mutationTypesList = ['childList', 'subtree', 'attributes'];

const callback = (mutation, observer) => {
   for(const mutation of mutationList){
      if(mutationTypesList.includes(mutation.type) {
      // do something
    }
  }
}
Roi
  • 97
  • 1
  • 6
  • what if I wanna compare true or false? I think this is not possible with includes – IhateReact Aug 16 '21 at 11:39
  • @IhateReact you mean that check `mutation.type` against `{attributes : true , childList : true , subtree : true};` ? Essentially, `[true, 'cat', 4].includes(mutation.type)` where `mutation.type === true` will work – Roi Aug 16 '21 at 11:45
0

You can put the strings against which you compare the variable in a list and use the .includes() function on the array/list.

  if(['childList', 'subtree', 'attributes'].includes(mutation.type)){
        //do your thing
    }
pks9906
  • 193
  • 8