Why do console.log(00);
and console.log(01);
print 0 & 1 in the browser console and not 00 & 01?
console.log(00); // prints 0;
console.log(01); // prints 1;
console.log(011); // prints 9;
console.log(0111); // prints 73;
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.
That is because JavaScript treats leading 0 as octal number and that is why you are getting the octal number(base 8).
You could use parseInt with radix to eliminate these kind of issues.
And the reason why console.log treats the input as octal is, by default console.log calls valueOf
method of input. If it doesn't returns anything it will call toString
method.
And the valueOf
method returns values like below:
00.valueOf() // 0
01.valueOf() // 1
011.valueOf() // 9
0111.valueOf() // 73
Reference:- http://javascript.info/tutorial/object-conversion
For your reference I've added the number system table
Evaluating
When executing console.log(stuff)
, before printing, stuff
is evaluated to see what is to be printed. This is why console.log(3+2)
prints 5
and not 3+2
. This has nothing to do with console.log
in particular, the evaluation is done before the execution of console.log
. Any function would behave the same way, it would be passed the evaluated 5
as parameter and not the initial 3+2
Parsing
Even before evaluating, there is another factor at play: parsing. Parsing is the first step of interpreting the source code and it refers to analysing the characters in the source code to figure out what logical constructs (tokens) they refer to.
The tricky bit here is that numbers can be written in a few ways:
1
, 15
- numbers written in decimal (base 10)01
, 017
- numbers written in octal (base 8)0b1
, 0b1111
- numbers written in binary (base 2)0x1
, 0xE
- numbers written in hexadecimal (base 16)All of these refer to the same 2 numbers - 1 and 15, but they are different graphical representations the same way you would consider 6
and 0000006
the same number.
Once the source code is parsed, the characters written in the source code are "replaced" by the actual number they represent. This means that even before the Javascript engine knows it has to do some printing the characters you have written are gone and what remains are the actual numbers you have referenced.
Annex B
While the main Javascript spec considers octal numbers only those starting with 0o
, the legacy syntax considers octal numbers those starting with 0
.
leading zero in console making it to base of 8.
console.log(00)=0
console.log(01)=1
console.log(011)=9 //0+8+1
console.log(0111)=73 //0+64+8+1
When you write console.log(00), the argument 00 is interpreted as number and so 0 is printed. On the other hand if you write console.log("00") 00 is interpreted as a string and 00 is printed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With