0

I have a condition as below to check the variables Qmart and linearstatus.
Though they have the values as required, my if statement is always going to the else condition. Is there some mistake I'm making for checking these values?

var Qmart = "A2";
var linearstatus  = "linear"

if (Qmart === ("E2" || "A2" || "B2" || "D2") && linearstatus == "linear") {
} else {
    alert("it is an else condition");
}
2
  • You are gonna have to compare them all one by one, or put them in an array and use find or indexOf. if (Qmart === "E2" || Qmart === "A2" ... ) { ... } Commented Dec 11, 2016 at 6:15
  • "E2" || "A2" || "B2" || "D2" => "E2" Commented Dec 11, 2016 at 6:16

3 Answers 3

3

Change the if condition to the following

if ((Qmart === "E2" || Qmart === "A2" || Qmart === "B2" || Qmart === "D2") && (linearstatus == "linear")) {

} else {
  alert("it is an else condition");
}

Hope it helps

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to check for multiple values you cannot use Qmart === ("E2" || "A2" || "B2" || "D2"), you need to check each condition separatelly:

if ((Qmart === "E2" || Qmart === "A2" || Qmart === "B2" || Qmart === "D2") && linearstatus == "linear") {

} else {
    alert("it is an else condition");
}

You might ask why your code did not throw any runtime error. The issue is that code

"E2" || "A2" || "B2" || "D2"

is a valid JavaScript code, and it returns first truthy value. This feature is called short-circuit evaluation and is used often in JavaScript. In your case above statement returns first truthy value, which is always "E2". This means that, your code is identical to

if (Qmart === "E2" && linearstatus == "linear")

and when Qmart is A2, then the condition evaluates to false and else statement is executed.

Comments

2

You could do something like this.

var QMart = "E2",
  linearstatus = "linear";

var conditions = ["E2", "A2", "B2", "D2"];
if (conditions.indexOf(QMart) !== -1 && (linearstatus == "linear")) {
  console.log("In truthy condition");
} else {
  console.log("it is an else condition");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.