0

The country_code in this case can be DE or GB.

var cc = country_code

if (cc.equals == "GB"){
    console.log("You're in the UK")
  }
  else {
    console.log("You're not in the UK")
}

Why is this statement throwing up incorrect responses?

EDIT:

The missing " was a typo. The solutions given haven't work so far.

I set country_code to be the text response of a XMLHttpRequest object. If that helps?

9
  • 5
    Don't need .equals, use cc === "GB". console.log(You're not in the UK") Missing start quote, ". Commented Jan 11, 2016 at 4:22
  • is country code is object or you are comparing wrong ? I highly doubt in this line if @Tushar comment is just a typo Commented Jan 11, 2016 at 4:24
  • Possible duplicate of What is the correct way to check for string equality in JavaScript? Commented Jan 11, 2016 at 4:24
  • @Tushar that should be an answer. Commented Jan 11, 2016 at 4:24
  • @EdCottrell What about dupe Commented Jan 11, 2016 at 4:25

4 Answers 4

2

You must use the Equal (==) operator to check if the value of cc is equal to the string literal "GB". Or you can use the Strict equal (===) operator to see if the operands are equal and of the same type.

Also the argument to the console.log call in the else branch must be within quotation marks, or else you'll get syntax error. String literals must always be enclosed in ' or ".

var cc = country_code;

if (cc == "GB"){
    console.log("You're in the UK")
}
else {
    console.log("You're not in the UK")
}
Sign up to request clarification or add additional context in comments.

2 Comments

you can also suggest strict checking with ===
@AnikIslamAbhi Good point. I've updated my answer to go into further detail in regard to your comment.
1

The country_code in this case can be DE or GB.

That means the variable country_code is a string.

So, cc.equals == "GB" will return undefined as there is no member property equals on the String prototype.

To compare two strings use equality operator == or strict equality operator ===.

if (cc === "GB") {

Also, in the else block, there is missing quote. It should be

console.log("You're not in the UK")
            ^

Here's complete code:

var cc = country_code;

if (cc === "GB") { // Use equality operator to compare strings
    console.log("You're in the UK");
} else {
    console.log("You 're not in the UK"); // Added missing quote
}

Comments

1
var cc = country_code;

    if (cc == "GB"){
        console.log("You're in the UK");
    }
    else {
        console.log("You're not in the UK");
    }

Comments

0

The reason why this was happening was because the text response from my XMLHttpRequest object was actually "GB " - three characters long.

I just cut it down to two and it worked fine: cc.substring(0,2)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.