1

I'm not clear on what exactly is wrong with the code below.
I want to ask the user to input a text string and to compare that to another text string. Then notify the user whether his string is alphabetically higher or lower than the stored value. When I test this in jsfiddle I only get the second alert message. Why does this happen?

This is my code:

var string1;
var string2;
string1 = prompt("Tell me your string1?");
string2 = "green";

if ("string1" > "string2")
    alert("Your string is alphabetically higher");
else
    alert("Your string is not alphabetically higher");
Idos
  • 15,053
  • 14
  • 60
  • 75
whada
  • 306
  • 3
  • 15
  • 1
    Possible duplicate of [comparing 2 strings alphabetically for sorting purposes](http://stackoverflow.com/questions/10198257/comparing-2-strings-alphabetically-for-sorting-purposes) – Oxi Jan 29 '16 at 12:29

5 Answers5

1

You're not comparing your variables at all, but the actual strings "string1" & "string2". This is why you always get the first alert, since "string1" > "string2" lexicographicaly (alphabetically).

Use:

if (string1 > string2)

This will fix your code and make it work, but a safer and better way to compare strings in javascript is to use localeCompare:

string1.localeCompare(string2);

/* Returns:

 0:  equal

-1:  string1 < string2

 1:  string1 > string2

 */
Idos
  • 15,053
  • 14
  • 60
  • 75
0

The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

string1.localeCompare(string2)
Bob Sponge
  • 4,708
  • 1
  • 23
  • 25
  • You should show the OP how to use this, since it is not obvious for beginners. I.e 0 is returned when equal... etc. – Idos Jan 29 '16 at 12:34
0

if you remove the quotes around the variable names, it'll work as advertised. otherwise you are comparing two strings and never checking the variables.

since "string1" > "string2" is simply always false, you're always going into the else block in the code you've posted

Leroy
  • 13
  • 2
0
var stringA = 'something';
var stringB = 'foobar';
var compareResult = stringA.localeCompare(stringB);

if (compareResult < 0) {
  console.log('a is before b');
} else if (compareResult > 0) {
  console.log('a is after b');
} else {
  console.log('a equals b');
}

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

Per Östlund
  • 1,224
  • 1
  • 8
  • 7
0

As Idos mentioned, you're creating two new strings and comparing them in your if statement, not the ones asked of the user.

"string1" > "string2"
// This compares the values "string1" and "string2"

string1 > string2
// This compares the contents of the variables string1 and string2, 
// in your case the user input and "green"
Mitch
  • 291
  • 2
  • 17