mohammed sameeh
mohammed sameeh

Reputation: 5099

JavaScript comparison failing

I'm trying to prompt for, then compare two values:

var x,y;
x = prompt("enter the first value","");
x = prompt("enter the second value","");

if( x > y)
{
  alert("x>y");
}
else if(x < y)
{
  alert("y>x")
}
else 
{
  alert("error");
}

Each time I run this, the alert("error") line is hit. What am I doing wrong?

Upvotes: 0

Views: 130

Answers (6)

vol7ron
vol7ron

Reputation: 42109

You're prompting for and assigning x twice, thus y is left undefined.

Anything undefined will not be considered true.

var x,y;
x = prompt("enter the first value","");
y = prompt("enter the second value","");

if      ( x > y ) {  alert("x>y");    } 
else if ( x < y ) {  alert("y>x");    } 
else              {  alert("error");  }

Upvotes: 0

mozillanerd
mozillanerd

Reputation: 560

Perhaps you did not intentioanlly write x= twice?

Upvotes: 0

Chris Laplante
Chris Laplante

Reputation: 29658

x=prompt("enter the first value","");
x=prompt("enter the second value","");

should be:

x=prompt("enter the first value","");
y=prompt("enter the second value","");

Upvotes: 0

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17762

Typo:

x=prompt("enter the first value","");
y=prompt("enter the second value","");

Upvotes: 1

rcravens
rcravens

Reputation: 8390

your second line should set y instead of x.

Upvotes: 0

Kirk Woll
Kirk Woll

Reputation: 77546

You are not assigning y:

x=prompt("enter the first value","");
x=prompt("enter the second value","");

Both assignments assign x.

Upvotes: 4

Related Questions