Skip to content Skip to sidebar Skip to footer

Comparing Strings In An If Statement

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

Solution 1:

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")
}

Solution 2:

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 stringsconsole.log("You're in the UK");
} else {
    console.log("You 're not in the UK"); // Added missing quote
}

Solution 3:

var cc = country_code;

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

Solution 4:

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)

Post a Comment for "Comparing Strings In An If Statement"