Why is string 11 less than string 3?
Strings are compared lexicographicaly. i.e. character by character until they are not equal or there aren't any characters left to compare. The first character of '11' is less than the first character of '3'.
> '11' < '3'
true
> '31' < '3'
false
> '31' < '32'
true
> '31' < '30'
false
If we use letters then, since b
is not less than a
, abc
is not less than aaa
, but since c
is less than d
, abc
is less than abd
.
> 'abc' < 'aaa'
false
> 'abc' < 'abd'
true
You can explicitly convert strings to numbers:
> +'11' < '3'
false
Why is one string greater than the other when comparing strings in JavaScript?
Because, as in many programming languages, strings are compared lexicographically.
You can think of this as a fancier version of alphabetical ordering, the difference being that alphabetic ordering only covers the 26 characters a
through z
.
This answer is in response to a java question, but the logic is exactly the same. Another good one: String Compare "Logic".
What is the cause? operators or use of strings?
I guess it is because it compare ascii values of chars and 3 had greater ascii value than 2. In string it compare char by char if 1 char is false it wont compare else
Why do JavaScript comparisons have different results for strings and for numbers?
"105.00" > "2.00"
is comparing strings instead of numbers.
Why is `12:34 123:45` equal to `false`?
Because of the ASCII code of 3
and :
. We know that the comparison between strings will be done by the dictionary rule. Hence, as the first difference is in the third location of two strings, the ASCII code of 3
and :
will determine the result of the comparison. As the ASCII code of :
is greater than 3
, you see the false as a result. See the ASCII code of them in the following.
console.log(":".charCodeAt(0));
console.log("3".charCodeAt(0));
Why in javascript 100 5 returns true?
When you use <
with strings, the code points of the each index of the strings are compared. The code point for 1 is 49, and the code point for 5 is 53, so '100' < '5'
, because 49 < 53.
console.log( '1'.charCodeAt(), '5'.charCodeAt());
Why does string to number comparison work in Javascript
Because JavaScript defines >=
and <=
(and several other operators) in a way that allows them to coerce their operands to different types. It's just part of the definition of the operator.
In the case of <
, >
, <=
, and >=
, the gory details are laid out in §11.8.5 of the specification. The short version is: If both operands are strings (after having been coerced from objects, if necessary), it does a string comparison. Otherwise, it coerces the operands to numbers and does a numeric comparison.
Consequently, you get fun results, like that "90" > "100"
(both are strings, it's a string comparison) but "90" < 100
(one of them is a number, it's a numeric comparison). :-)
Is it okay to have this comparison like this or should I use parseInt() to convert x to integer ?
That's a matter of opinion. Some people think it's totally fine to rely on the implicit coercion; others think it isn't. There are some objective arguments. For instance, suppose you relied on implicit conversion and it was fine because you had those numeric constants, but later you were comparing x
to another value you got from an input field. Now you're comparing strings, but the code looks the same. But again, it's a matter of opinion and you should make your own choice.
If you do decide to explicitly convert to numbers first, parseInt
may or may not be what you want, and it doesn't do the same thing as the implicit conversion. Here's a rundown of options:
parseInt(str[, radix])
- Converts as much of the beginning of the string as it can into a whole (integer) number, ignoring extra characters at the end. SoparseInt("10x")
is10
; thex
is ignored. Supports an optional radix (number base) argument, soparseInt("15", 16)
is21
(15
in hex). If there's no radix, assumes decimal unless the string starts with0x
(or0X
), in which case it skips those and assumes hex. Does not look for the new0b
(binary) or0o
(new style octal) prefixes; both of those parse as0
. (Some browsers used to treat strings starting with0
as octal; that behavior was never specified, and was [specifically disallowed][2] in the ES5 specification.) ReturnsNaN
if no parseable digits are found.Number.parseInt(str[, radix])
- Exactly the same function asparseInt
above. (Literally,Number.parseInt === parseInt
istrue
.)parseFloat(str)
- LikeparseInt
, but does floating-point numbers and only supports decimal. Again extra characters on the string are ignored, soparseFloat("10.5x")
is10.5
(thex
is ignored). As only decimal is supported,parseFloat("0x15")
is0
(because parsing ends at thex
). ReturnsNaN
if no parseable digits are found.Number.parseFloat(str)
- Exactly the same function asparseFloat
above.Unary
+
, e.g.+str
- (E.g., implicit conversion) Converts the entire string to a number using floating point and JavaScript's standard number notation (just digits and a decimal point = decimal;0x
prefix = hex;0b
= binary [ES2015+];0o
prefix = octal [ES2015+]; some implementations extend it to treat a leading0
as octal, but not in strict mode).+"10x"
isNaN
because thex
is not ignored.+"10"
is10
,+"10.5"
is10.5
,+"0x15"
is21
,+"0o10"
is8
[ES2015+],+"0b101"
is5
[ES2015+]. Has a gotcha:+""
is0
, notNaN
as you might expect.Number(str)
- Exactly like implicit conversion (e.g., like the unary+
above), but slower on some implementations. (Not that it's likely to matter.)Bitwise OR with zero, e.g.
str|0
- Implicit conversion, like+str
, but then it also converts the number to a 32-bit integer (and convertsNaN
to0
if the string cannot be converted to a valid number).
So if it's okay that extra bits on the string are ignored, parseInt
or parseFloat
are fine. parseInt
is quite handy for specifying radix. Unary +
is useful for ensuring the entire string is considered. Takes your choice. :-)
For what it's worth, I tend to use this function:
const parseNumber = (str) => str ? +str : NaN;
(Or a variant that trims whitespace.) Note how it handles the issue with +""
being 0
.
And finally: If you're converting to number and want to know whether the result is NaN
, you might be tempted to do if (convertedValue === NaN)
. But that won't work, because as Rick points out below, comparisons involving NaN
are always false. Instead, it's if (isNaN(convertedValue))
.
Compare two strings with '' and '' operators in JavaScript
As said above, the formal specification is in the standard: http://www.ecma-international.org/ecma-262/7.0/#sec-abstract-relational-comparison , in layman's terms the logic is like this:
1) String vs String
Split both strings into 16-bit code units and compare them numerically. Note that code units != characters, e.g. "cafè" < "cafè"
is true
(really).
2) String vs other primitive
Convert both to numbers. If one of them is NaN
, return false
, otherwise compare numerically. +0
and -0
are considered equal, +/-Infinity
is bigger/smaller than anything else.
3) String vs Object
Try to convert the object to a primitive, attempting, in order, [Symbol.toPrimitive]("number")
, valueOf
and toString
. If we've got string, proceed to 1), otherwise proceed to 2). For arrays specifically, this will invoke toString
which is the same as join
.
Differences between C++ string == and compare()?
This is what the standard has to say about operator==
21.4.8.2 operator==
template<class charT, class traits, class Allocator>
bool operator==(const basic_string<charT,traits,Allocator>& lhs,
const basic_string<charT,traits,Allocator>& rhs) noexcept;
Returns: lhs.compare(rhs) == 0.
Seems like there isn't much of a difference!
How are strings compared?
From the docs:
The comparison uses lexicographical
ordering: first the first two items
are compared, and if they differ this
determines the outcome of the
comparison; if they are equal, the
next two items are compared, and so
on, until either sequence is
exhausted.
Also:
Lexicographical ordering for strings uses the Unicode code point number to order individual characters.
or on Python 2:
Lexicographical ordering for strings uses the ASCII ordering for individual characters.
As an example:
>>> 'abc' > 'bac'
False
>>> ord('a'), ord('b')
(97, 98)
The result False
is returned as soon as a
is found to be less than b
. The further items are not compared (as you can see for the second items: b
> a
is True
).
Be aware of lower and uppercase:
>>> [(x, ord(x)) for x in abc]
[('a', 97), ('b', 98), ('c', 99), ('d', 100), ('e', 101), ('f', 102), ('g', 103), ('h', 104), ('i', 105), ('j', 106), ('k', 107), ('l', 108), ('m', 109), ('n', 110), ('o', 111), ('p', 112), ('q', 113), ('r', 114), ('s', 115), ('t', 116), ('u', 117), ('v', 118), ('w', 119), ('x', 120), ('y', 121), ('z', 122)]
>>> [(x, ord(x)) for x in abc.upper()]
[('A', 65), ('B', 66), ('C', 67), ('D', 68), ('E', 69), ('F', 70), ('G', 71), ('H', 72), ('I', 73), ('J', 74), ('K', 75), ('L', 76), ('M', 77), ('N', 78), ('O', 79), ('P', 80), ('Q', 81), ('R', 82), ('S', 83), ('T', 84), ('U', 85), ('V', 86), ('W', 87), ('X', 88), ('Y', 89), ('Z', 90)]
Related Topics
How to Set Textarea Scroll Bar to Bottom as a Default
Dynamically Add CSS to Page via JavaScript
Fix First Column of a Bootstrap Table
How to Get Color Value from Gradient by Percentage with JavaScript
Affix Is Not Working in Bootstrap 4 (Alpha)
Jquery/JavaScript Opacity Animation with Scroll
Clean Way to Programmatically Use CSS Transitions from Js
Center an Image Vertically and Horizontally Using CSS
Set Height of <Div> = to Height of Another <Div> Through .Css
How to Get a Floating Footer to Stick to the Bottom of the Viewport in Ie 6
IE9: Why Setting "-Ms-Transform" Works from CSS, But Not with Jquery.Css()
How to Combine Jquery Animate with CSS3 Properties Without Using CSS Transitions
Check If Element Exists in Jquery
JavaScript Promises - Reject VS. Throw
Correct Way to Convert Size in Bytes to Kb, Mb, Gb in JavaScript
Rerender View on Browser Resize with React