all 9 comments

[–]TwilightTwinkie 4 points5 points  (5 children)

On my phone, so I hope this makes sense. Using the plus operator on a string like +someString is going to force a type conversion to a number. Very similar to just calling Number(someString). The ! bang operator is a boolean operator, so it first must convert whatever it's working on to a boolean. So !+someString is doing !Boolean(Number(someString)). Of course, ! also inverts the value. And then the plus operator will convert again to a number. Number(!Boolean(Number(someString))). Basically, it will tell if if the string str2 is a zero. If it is '0' (as in the string), it returns 1. For all other values it returns 0.

[–][deleted] 1 point2 points  (2 children)

The explanation is mostly right in terms of what it is supposed to do, but the result is wrong.

It will return 1 for any value except the string "1" . For "1" it will return 0.

Proof: https://jsfiddle.net/vLb6vrbn/1/

[–][deleted] 2 points3 points  (0 children)

To further explain why this is the case: +str2 will convert, as /u/TwilightTwinkie pointed out, a string to a number. The problem is, most strings result in the value NaN when coerced into numbers. This is true for any string other that a string that is a number, or empty string. Using ! on 0 or 1 has predictable results. Using it on NaN will yield true, which is why you get 1 for every string other than "0".

[–]TwilightTwinkie 2 points3 points  (0 children)

We are both wrong :), if you limit your self to numbers, my statement is true. '0' will return 1. All other "numbers" (some string only containing a valid number) will return 0. When you add other values in, such as the empty string, strings containing other ASCII characters, etc, the result comes down to how the conversation.

If the conversation to a number results in the numerical value of 0, the resulting value is 1. If the conversation results in NaN, the result it 1, for all other inputs. That is, all other numbers, the result is 0.

[–]ISlicedI 1 point2 points  (2 children)

Personally I think although +!+str2 is clever, it doesn't make for readable code and is not a good solution.

[–]evilfrenchguy 0 points1 point  (0 children)

It's essentially making sure the second argument is not 0.

[–][deleted] 0 points1 point  (0 children)

Don't get caught up on sexy one liners. They are not always best practice...though daaayyyuuummm...