Reputation: 932
Why javascript is create confusion with following code?
var a = 10; //will return output 10
var b = 010; //will return output 8
Upvotes: 0
Views: 102
Reputation: 1075805
The issue is that you're using loose mode and in loose mode in most environments a leading 0
followed by a digit indicates a legacy octal literal. In octal, 010
(which is to say, `10 octal) is the number eight. Octal is base 8, so the rightmost digit is the "ones" column, the one just left of it is the "eights" column, the one just left of that is the "sixty-fours" (8 x 8) column, etc. (Just like in decimal, the rightmost column is the "ones," the next one to the left is the "tens," the next to the left is the "hundreds," etc.)
Octal Decimal ------ ------- 0 0 1 1 ... 7 7 10 8 11 9 12 10 13 11 14 12 15 13 16 14 17 15 20 16 ...
To fix it:
Use strict mode ("use strict";
at the top, and/or use modules which are strict by default), and
Don't start a decimal literal with 0
. :-)
Upvotes: 0
Reputation: 56
010 is an octal representation of denary value 8.
If you don't know about numbers system, there are basically 4 ways you can represent numbers in programming
Read more about number system here
If you want to represent a octal number in JavaScript, you put 0 in front on any values, if you want to represent a value in hexadecimal it can be achieved by putting 0x in front of any number.
For Example,
var a= 010; //8 in decimal
var b= 0xF; //15 in decimal
Learn more about number in JavaScript here
Upvotes: 2
Reputation: 234875
From the earliest versions of C (1978), a leading zero has been used to denote an octal literal.
This has carried over to C++, Java, and even Javascript.
Some more courageous languages (Python 3 for example) are moving to 0o
for an octal literal, as these days the leading 0 notation seems to do more harm than good.
Upvotes: 1
Reputation: 1107
If number is leading with 0 the Javascript will in interpret as octal number. Never write a number with a leading zero (like 07). Some JavaScript versions interpret numbers as octal if they are written with a leading zero.
Upvotes: 0