4 ms·
> if(~someStringOrArray.indexOf(searchTerm)) Do you think the person maintaining your code 2-5 years from now will understand that easily and quickly? For mai
by grecy 12y ago
> if(~someStringOrArray.indexOf(searchTerm))
Do you think the person maintaining your code 2-5 years from now will understand that easily and quickly?
For maintenance, it's important to be as clear as possible, not as tricky as possible.
- nmjohn 12y agoWhich is why I only use it on solo projects. That being said, ~indexOf is hardly tricky. if(string.indexOf(term)) is far trickier, because if you didn't realize it returning 0 was a positive result, you easily could write it without a -1 check and not notice it during testing if no values had an index of 0. Then months later you would have a hell of a time debugging it because it would look so innocuous. On the other hand, by including the tilde, you ensure two things: 1.) Future developer knows what it does and has no problems. 2.) Future developer hasn't seen it before and goes straight to google to see what it does - at which point they learn and now will recognize it in the future. So at the end of the day, by using a ~, it is explicitly clear that indexOf() should not be used directly as a coerced boolean, and it ensures that anyone touching the code will either know or learn why.
- vegedor 12y ago>On the other hand, by including the tilde, you ensure two things: 1.) Future developer knows what it does and has no problems The premises was that the future dev won't know. It was hard to write, it should be hard to read moderately applies, I guess.
- zamalek 12y agoIf you come from a C background you would probably parse the intent of that immediately. Bitwise complement is pretty basic stuff and is probably what the C compiler winds up optimizing `!<int>` to anyway. I'm guessing that the only reason it's used here is character optimization.