3 ms·
A fun guess-the-output to illustrate the implicit/permissive nature of JS: console.log(parseInt("020" + 020, base=5)) Most languages would throw an error b
by cranium 4y ago
A fun guess-the-output to illustrate the implicit/permissive nature of JS:
console.log(parseInt("020" + 020, base=5))
Most languages would throw an error because "020" + 020 = "02016" and we try to parse this in base 5. However, the parseInt function silently stops reading the input if it encounters an invalid character.
Language design nitpicks:
- the octal prefix is kind of difficult to see and could lead to accidental conversions, at least the clearer representation 0o20 is also understood.
- the parseInt function understands the prefix 0x, but not 0b, 0o and only when the base is 16 or not set
- tgv 4y agoWhy write "base=5"? That makes it a variable, not a python-style named argument.
- jeroenhd 4y agoI suppose it works as a poor man's named argument. You still need to follow the argument order, but the code might be slightly more readable at the expense of creating random variables all over your code. The expression `a = 5` evaluates to 5 after all, which allows things like `a = b = c = d = 0` or the listed `let a = b = 5` which can cause confusion.
- wonderbore 4y ago> I suppose it works as a poor man's named argument. Sure, if by “poor man” you refer to the guy who has to debug that “code”. Name a variable with an existing or unwritable `window` property and enjoy. Don’t do this stuff, use a linter and a decent editor that can do this automatically.
- conaclos 4y agoMoreover in a ESM, this could lead to an error whether base is not defined.
- cranium 4y agoMy bad, too much Python lately. I wanted to be more explicit about this argument and briefly tested the syntax in a Node console. It works, but... I didn't catch the atrocious side effect. Thanks for pointing the footgun !