Javascript variable with leading zeros

Javascript behaves differently with values ​​having leading zeros. alert (b) - prints a different value.

var a = 67116; var b = 00015; alert(a); alert(b); 

I am more interested in knowing which conversion is applied here in javascript inside alert (b)? (If I have them in double quotes, they work fine.)

+4
source share
3 answers

Since js is weakly typed, it thinks

 var b = 00015 

- octal number

see this question for solution

+3
source

The leading 0 makes the value an octal literal, so the value you put will be interpreted as a base integer.

In other words, 015 would be equivalent to parseInt('15', 8) .

+3
source

As the other answers say, leading zeros make a number an octal literal. The decimal representation of the octal "15" is "13".

Note that there is no reason to use leading zeros in numeric literals unless you really want to be interpreted as octal. I mean, do not use var b = 00015 . If you get this value from user input, then it will be a string (ie "00015" ), and you can convert it to decimal using parseInt :

 var b = "00015"; // or var b = document.getElementById('some_input').value var numB = parseInt(b, 10); // 15 
+1
source

Source: https://habr.com/ru/post/1486287/


All Articles