Don't use + or | for parsing Integer in JavaScript
you can simple try
+'01010101'
or
'01010101' | 0
so, don't use them, just parseInt('01010101', 2)
Written by Nos
Related protips
2 Responses
Instructing people to use one method while not using another without any explanation does not do the community any good. Please stop and explain the purpose of this pro-tip.
For the record, both the unary +
operator and bitwise operators |
coerce variables to numbers on a base 10. This works for most cases unless the number needs to be interpretted as binary. In that case, you may also use parseInt
with the radix (base) of 2
to interpret it.
If you are going to use parseInt
without specifying a radix, beware that it will attempt to do octal
if the number begins with 0
and otherwise fall back to base 10. This is why most people say it is best to always specify a radix with parseInt
. I use +
since it is simpler and has the same effect.
I don't see anything wrong with +'01010101'
or '01010101' | 0