user3213861
user3213861

Reputation: 145

Expression results into error

I have a simple question for you and this is bothering me for the whole day now. I have an expression, it's like this i have 2 variables for example x and y. x will have a value of 7 and I want y to be always greater than x. If the entered number is less than x it will alert a message.

y.value > x.value
alert("the number must be greater than X")

The problem is when I enter 10,11,12 and any 2 digit number greater than 7 it displays the alert box. I think because youll enter the first digit first so the program reads it. can anyone help me with this logic thanks

Upvotes: 0

Views: 44

Answers (1)

HSY
HSY

Reputation: 61

You will need to check if x.value and y.value are set as string or number.

String '12' is less than '7' while number 12 is greater than 7.

If they are strings, you may want to convert them to number and compare them.

'12' > '7'
false

12 > 7
true

// STRING comparison
var x = { value: '7' };
var y = { value: '12'};
y.value > x.value;
false

// NUMBER comparison
var x = { value: 7 };
var y = { value: 12 };
y.value > x.value;
true

// convert STRING to NUMBER and compare
var x = { value: '7' };
var y = { value: '12' };
+y.value > +x.value; // conversion
true

Upvotes: 1

Related Questions