AmazingDayToday
AmazingDayToday

Reputation: 4272

How can I simplify the if statement in JS

This is the code:

public noArtistBeingEdited(): boolean {
    if (this.isFirstNameBeingEdited()) {
        return false;
    }
    if (this.isLastNameBeingEditable()) {
        return false;
    }
    return true;
}

How can I simplify it?

Upvotes: 0

Views: 437

Answers (3)

Luís Ramalho
Luís Ramalho

Reputation: 10208

You could simplify by going step-by-step, so initially you can reduce the two statements into one by merging them together. Since they return the same, os either the first or last need to be true in order for it to return false.

public noArtistBeingEdited(): boolean {
    if (this.isFirstNameBeingEdited() || this.isLastNameBeingEditable()) {
        return false;
    }
    return true;
}

Then you can see that if the whole this.isFirstNameBeingEdited() || this.isLastNameBeingEditable() is true then it will return false. So you could just put the whole statement inside brackets as it acts as one.

(this.isFirstNameBeingEdited() || this.isLastNameBeingEditable()) === false

So now you know that if you invert that whole statement then you'll get true, so you can just

!(this.isFirstNameBeingEdited() || this.isLastNameBeingEditable())

The above means that they need to be both false for the function to return true:

let fn = (a, b) => {
  if (a) {
    return false;
  }
  if (b) {
    return false;
  }
  return true;
};


console.log(fn(true, true)); // false
console.log(!(true || true)); // false

console.log(fn(false, false)); // true
console.log(!(false || false)); // true

console.log(fn(false, true)); // false
console.log(!(false || true)); // false

console.log(fn(true, false)); // false
console.log(!(true || false)); // false

Upvotes: 0

Ted Brownlow
Ted Brownlow

Reputation: 1117

public noArtistBeingEdited(): boolean {
    return !this.isFirstNameBeingEdited() && !this.isLastNameBeingEditable()
}

Your expresion reduces to neither of the two checks i.e. NOT A AND NOT B

Upvotes: -1

Jack Bashford
Jack Bashford

Reputation: 44107

Use an OR (||) operator:

public noArtistBeingEdited(): boolean {
    if (this.isFirstNameBeingEdited() || this.isLastNameBeingEditable()) {
        return false;
    }
    return true;
}

Upvotes: 4

Related Questions