2

I was sorting a string/array of integers in lexicographical order.
A case came when i had to sort a string containing "022" using array.sort. I don't know why it is equating that equal to "18" when being printed.

var l = [022,12];
l.sort();
(2) [12, 18] => output

What is the reason behind this and how to correct it?

2 Answers2

1

This isn't specific to the sort. If you just type 022 into a console, you'll get back 18. This is because 022 is being interpreted as an OctalIntegerLiteral, instead of as a DecimalLiteral. This is not always the case however. Taking a look at the documentation:

Note that decimal literals can start with a zero (0) followed by another decimal digit, but If all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. This won't throw in JavaScript, see bug 957513. See also the page about parseInt().

EDIT: To remove the leading 0s and interpret the 022 as a decimal integer, you can use parseInt and specify the base:

parseInt("022", 10);
> 22
stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53
1

I recommend to "use strict"; so that 022 will produce a syntax error instead of octal number:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_octal

Aprillion
  • 21,510
  • 5
  • 55
  • 89