Why is 16 equal to 020 in Javascript?

Asked

Viewed 114 times

10

I was comparing CPF’s when I got the following expression:

if(16 == 020){
    console.log(true)
}else{
    console.log(false)
}

The result of this expression is true, I’d like to understand why.

1 answer

11

The number 020 is being interpreted as octal - i.e., base 8, using the digits 0 to 7 to represent the values. In Javascript, literal values started with zero are interpreted as octal, except in strict mode of language. 020 octal 16 in base 10.

Another possible notation in the language for literal octais is with the prefix 0o or 0O (zero-oh). Thus, the decimal value 16 can also be represented as 0o20 or 0O20.

  • 4

    Interesting to note that it is considered octal only if it is a valid octal value. When invalid, it remains as decimal: 089 is decimal 89 itself. Only using notation with letter O, 0o89, error

  • 2

    Well noted. A little dangerous rely on the zero on the left, therefore. So until that syntax is turned off in Strict mode.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.