2

console.log() for numbers is behaving differently.

Below findings are interesting. Any explanation?

console.log(1) - 1

console.log(01) - 1

console.log(12) - 12

console.log(012) - 10

console.log(0123) - 83

console.log(123) - 123

EDIT

Found this in MDN documentation:

Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8).

Decimal integer literal consists of a sequence of digits without a leading 0 (zero).
Leading 0 (zero) on an integer literal indicates it is in octal. Octal integers can include only the digits 0-7.
Leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F.
Octal integer literals are deprecated and have been removed from the ECMA-262, Edition 3 standard (in strict mode). JavaScript 1.5 still supports them for backward compatibility.
Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
  • 1
    `console.log(012); // 10` when debugging something weird like this, reduce the code down to eliminate methods that may not be related. – Kevin B Nov 22 '13 at 20:44
  • @KevinB - you're right. Should've done that. Thought that the function is behaving weird. Not to be. – Venkata Krishna Nov 22 '13 at 20:57

1 Answers1

3

This has nothing to do with jQuery; it's just a feature / quirk of ECMAScript (and therefore JavaScript). Numeric literals beginning with 0 are interpreted in octal, rather than decimal (except in strict mode, in which case it produces a syntax error).

You can verify this by observing 012 === 10 and 0123 === 83.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • thank you. I calculated it & everything was matching but wasn't sure why octal. – Venkata Krishna Nov 22 '13 at 20:45
  • You can "trim" leading zeroes by using `Number('0123')` – Noah Heldman Nov 22 '13 at 20:49
  • @NoahHeldman in this case it might be better to use _parseInt_ or _parseFloat_ than _Number_. – Paul S. Nov 22 '13 at 20:51
  • 1
    @Paul S. True, you can use parseInt, but for leading zeroes, you will need the radix component to get the 123 value: parseInt('0123', 10) – Noah Heldman Nov 22 '13 at 21:04
  • 1
    @NoahHeldman yes, the _radix_ should be given too, however if the browser is standards-compliant you don't actually _need_ it; [**spec**](http://es5.github.io/#x15.1.2.2) (base 8 never gets assumed). – Paul S. Nov 23 '13 at 10:49