user15718118
user15718118

Reputation:

Why doesnt my react if statement work with "or"

I am trying to get a console.log when my newPlan does not equal one of the selected options but it only works without the or statement "||"

Where am I going wrong?

      if(newPlan !== "monthlyPlan" || "yearlyPlan"){
    console.log("test2")
    this.setState({
      errorState: "error"
  });
  }

Upvotes: 0

Views: 48

Answers (2)

Muhammad Jaan
Muhammad Jaan

Reputation: 281

   Just give condition in both cases,

 if(newPlan !== "monthlyPlan" ||newPlan !=="yearlyPlan"){
    console.log("test2")
    this.setState({
      errorState: "error"
  });
  }

Upvotes: 0

PixAff
PixAff

Reputation: 329

if(newPlan !== "monthlyPlan" && newPlan !== "yearlyPlan"){
    console.log("test2")
    this.setState({
      errorState: "error"
  });
  }

EDIT - Explanation:

The && operator only becomes true if all conditions are true. In your case: if newPlan !== "monthlyPlan" is true and newPlan !== "yearlyPlan" is false the whole block becomes false.

Upvotes: 2

Related Questions