dush
dush

Reputation: 209

javascript: use of greaterthan with strings

I am confused in understanding this "9">"099" returns true and "9">"99" returns false(9 is just an example, it is happening like "x">"xabc" returns false and "x">"abc" returns true, where a is smaller than x but abc is greater tha x and a,b,c,x are numbers). Thanks in advance.

Upvotes: 10

Views: 6949

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074989

it is happening like "x">"xabc" returns true and "x">"abc" returns false, where a is smaller than x but abc is greater tha x and a,b,c,x are numbers)

Yes (except that "abc" is not greater than "x", and those are characters, not numbers). It's a textual comparison, the numbers in the strings are not converted to numbers before comparing them. So the comparison works character by character, stopping the first time it finds a difference. In your "99" > "099" case, since the "9" in the left-hand string is greater than the "0" in the right-hand string, the result is determined by just the first character. (The same thing happens in "x" > "abc", because the "x" is greater than the "a".)

Note that there's a very big difference between:

console.log("99" > "099"); // "true"

and

console.log(99 > "099"); // "false"

In the latter case, because one of the operands is a number, the JavaScript engine will try to convert the other operand into a number and then compare the numbers. In the former case, because both operands are strings, it won't, it'll do a textual comparison.

Side note: Be careful of numeric strings starting with 0 (like "099"). If they end up being implicitly converted to a number, they may get treated as octal (base 8) depending on the JavaScript engine being used.

Upvotes: 14

Saswat
Saswat

Reputation: 12846

x>abc is returns true because x has ascii value more than a

but x>xbc is false though x has ascii value equal to x, but for the second character in both the string, the first string x has only one character, while the second string xbc has b as second character..

in x>abc

x is compared with a, when in first character position x is greater than a, hence it returns true

in second example x>xbc, first x is compared with x, which returns 0, since both have same ascii value..

but then b is compared with "" since "x" has only "x" while "xbc" has "b" as second charatcer.. being in existence hence xb is greater than x

so it returns false

Upvotes: 3

Related Questions