Srinivas
Srinivas

Reputation: 339

Multiple comparisons in an if statement using the logical OR operator is not working in JavaScript

I am checking in following way, But its not working. When I am using single statement it's working. i.e (NodeName !== "Active")

   function ClientCandidateMenuNodeClicked(sender, eventArgs) {
        var node = eventArgs.get_node();
        var NodeName=node.get_text();
        if( (NodeName !== "Active") || (NodeName !== "Recently Added") || (NodeName !== "Added") )
         {   
           if (NodeName != null)
           {
              alert(NodeName);
           }
        }
          node.toggle();
    }

Upvotes: 1

Views: 133

Answers (3)

user3392207
user3392207

Reputation: 108

Try this

if( NodeName !== "Active" || NodeName !== "Recently Added" || NodeName !== "Added" ) {   
  alert(NodeName);
}

Upvotes: -1

Bergi
Bergi

Reputation: 664336

The NodeName is always not "Active" or not "Recently Active" or not "Added". You want to use

if (NodeName !== "Active" && NodeName !== "Recently Added" && NodeName !== "Added" && NodeName != null) {
    alert(NodeName);
}

or

if (!(NodeName === "Active" || NodeName === "Recently Added" || NodeName === "Added") && NodeName != null) {
    alert(NodeName);
}

Upvotes: 1

James Allardice
James Allardice

Reputation: 165951

Your logic is wrong. If the value of NodeName is "Recently Added" the first thing that happens is a comparison to "Active" which evaluates to true (because they are not the same). Because the first condition evaluates to true the whole condition is considered true and the alert is executed.

You need to change your "ors" to "ands" (notice that I've removed all those parentheses too... you don't need them here):

if (NodeName !== "Active" && NodeName !== "Recently Added" && NodeName !== "Added") {
    // Do stuff
}

Upvotes: 5

Related Questions