Search code examples
javascriptecmascript-5

How can this conditional be shortened?


if (!this.initialized || (typeof this.activeId !== 'undefined' && options.qualification_id !== this.activeId)) {
    //Stuff
}

I want to execute code if the this.initialized flag is false or this.activeId value isn't the same as options.qualification_id. I have to check if this.activeId is defined or not because Javascript will return true in the case of undefined !== this.activeId. The above is the conditional I've come up with, but I hate how long it is. What would be the shortest way to write it?


Solution

  • If the valid values for this.activeId when it's defined are all truthy (e.g. it can't be 0, false, or null), you can use:

    if (!this.initialized || this.activeId && options.qualification_id != this.activeId)