Skip to content

Comment on Why ++[[]][+[]]+[+[]] = 10 in JavaScriptparent

Comments

What should the unary + operator do except for type coercion into a number? Or are you saying it should only work on strings?

It just doesn't seem like something that would happen accidentally, there's no reason to put + on something unless you are explicitly trying to coerce it into a number. It's not like unary minus where -x; could have some other semantic meaning for something that is already a number and you make a mistake and give it an array (which javascript has, and I think is a much more likely source of error than the unary plus).

Using an array (or a string for that matter) where only a number should be is an error. I'd like to see an exception thrown and the current JS uncaught-exception-handler would be invoked, assuming something else catches it.

If I want an array to be a number, I'll call .Count on the array or whatever the applicable property I want is.

I don't think you understand what I am trying to say.

The unary '+' operator is completely pointless if something is already a number, it is a no-op. Literally the only time anyone would ever type +x is if x is not a number, if someone chose to write +x and x turned out to unexpectedly be an array, pretty much the only thing that you know they were thinking of when they wrote the + was that they thought x isn't a number; maybe a string if they were using +x instead of parseFloat(x), but definitely not a number.

It just isn't a reasonable example of a situation where an array is being used where a number should be, +x where you know that x is a number would make no sense. If you talk about -x then that is completely different, people who write -x almost certainly expect it to be a number, and -[] === 0. Unary plus is just not the right example for awful type coercion here.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.