-1
if(stringName.charAt(0) != 'Q' || stringName.charAt(0) != 'W' || stringName.charAt(0) != 'E'){

        SetID = "Yes";

    }

The above code when I use alert to popup the windows the value of My.String.charAt(0) is returning the correct value but I don't know why it goes inside the if statement and change the value of SetID to Yes

I'm trying to figure out what is wrong with it and really can't see anything

SetID is initialize to No

3
  • 1
    nipick: you really should store stringName.charAt(0) in a variable and use that instead of doing the look up multiple times. Commented Apr 6, 2012 at 13:50
  • @epascarello yes I did store it in my real code :D Commented Apr 6, 2012 at 13:51
  • This question is similar to: != operator not working in while loop condition when combined with || OR. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jan 5 at 14:09

3 Answers 3

9

You're using || but you probably mean && ...

The way it is now, it'll always be true. "If the character is not 'Q', or it's not 'W', or it's not 'E', then ..." — even if it is one of those characters, it will not be the others, so the expression evaluates to true.

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

1 Comment

OMG how stupid I'm really I should have thought of that logic once again.
1

Let's break down your statement.

MyString.charAt(0) != 'Q'

Okay, so if it's not Q then it continues.

||

So if the character is Q, continue along the chain.

MyString.charAt(0) != 'W'

By this point we've established that either the character is NOT Q (in which case SetID = "Yes" is run), or it is IS Q. But if it is Q, then clearly it is not W, therefore this next condition is true and SetID = "Yes" is run.

You see? No matter what the character is, it passes the test.

I think you meant to use &&, not ||. If you use &&, then the SetID = "Yes" is only run if the character is NONE OF Q, W or E.

Comments

1

Not an answer [too much code for a comment], but another possible solution using a reg exp

var stringName = "Quick";
if( (/^[QWE]/).test(stringName) ){
   SetID = "Yes";
}

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.