4 ms·
Learning about bitwise operators (and everything they entail - so binary in general, endianness, etc) was without a doubt the most beneficial thing I've ever do
by nmjohn 12y ago
Learning about bitwise operators (and everything they entail - so binary in general, endianness, etc) was without a doubt the most beneficial thing I've ever done for my programming abilities.
It was a complete eye opener to how computers work on a far more fundamental level than any other aspect of programming had previously revealed to me.
For anyone without a traditional CS educational background, if you don't know much about bitwise operations or binary, I highly recommend sitting down and spending a few hours exploring them - it will make you think about certain aspects of programming in a very different manner, which - at least for me - resulted in writing much better code.
Aside: While the double tilde is handy, I use the single tilde operator far more often in javascript. If you precede an indexOf statement with a tilde, it essentially turns `indexOf` into `contains`.
if(~someStringOrArray.indexOf(searchTerm))
It works because indexOf returns the index the term is found at, or -1 if it isn't found. This means 0 is actually a successful result, but Boolean(0) = false. But bitwise NOT will clear all of that up:
~(-1) = 0 (evaluates as false)
~(0) = -1 (evaluates as true)
Edit: I'm not suggesting everyone go off and use ~indexOf all the time - I was simply sharing a related javascript bitwise "trick".
- zoul 12y agoI would probably hate you for not writing plain “!=-1” instead.
- serve_yay 12y agoNo kidding, "clever" stuff like that drives me nuts.
- tlrobinson 12y agoYou definitely should learn bitwise operators, but if other people have to work with your code I'm not generally in favor of applying them in clever ways where there's a slightly more verbose but much more readable solution (e.x. "~x.indexOf(y)" vs "x.indexOf(y) !== 0"... just type the extra 3 characters)
- juhq 12y agoAs a rule of thumb, when ever one thinks that "wow, this code I just wrote is really clever", it should be a sign to sit back, take another approach and rewrite that code. Clever code almost always means that in hindsight it's terrible and will introduce bugs. In my opinion "x.indexOf(y) !== 0" is a lot more clearer and will immediately tells other developers what is happening. No point in saving space code, that's why we have minification libraries.
- lstamour 12y agoNobody needs this correction, I hope, but to be clear, it's !== -1 that we're replacing with ~. Then again, maybe this stands as a valid reason to be explicit in the first place. ;-)
- tracker1 12y agoA perfect example of why "~x.indexOf(y)" may actually be better... you just messed up, as the alternative should be "x.indexOf(y) !== -1" or "x.indexOf(y) >= 0" or "x.indexOf(y)+1" ... In any case, it's all a matter of style... because if you don't know that indexOf will return 0 for a positive match, you will still mess up.
- Cthulhu_ 12y agoOr someString.contains(searchTerm) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- nmjohn 12y ago> This is an experimental technology, part of the Harmony (ECMAScript 6) proposal. It only works in firefox and if I remember correctly, it is no longer part of the latest ECMA 6 spec.
- 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.
- imaginenore 12y agoAnd that's how you create unreadable code. Things like that are only acceptable if you're optimizing a bottleneck.
- chrismorgan 12y ago~x.indexOf(…) would be “starts with” rather than “contains”, for negative numbers such as -2 (from ~1) are truthy.
- nmjohn 12y ago> ~x.indexOf(…) would be “starts with” rather than “contains”, for negative numbers such as -2 (from ~1) are truthy. Nope, here's an example you can run it run in your console: function contains(needle, haystack) { return Boolean(~haystack.indexOf(needle)); } var haystack = "The quick brown fox jumps over the lazy dog"; console.log(contains("The", haystack)); console.log(contains("dog", haystack)); console.log(contains("brown fox jumps", haystack)); Here are three potential cases: haystack.indexOf('dog') = 40 -> truthy ~40 = -41 -> truthy haystack.indexOf('The') = 0 -> falsey (WRONG) ~0 = -1 -> truthy (FIXED) haystack.indexOf('nope') = -1 -> truthy (WRONG) ~-1 = 0 -> falsey (FIXED)
- Igglyboo 12y agoindexOf will only return -1, 0, or a positive integer
- ttty 12y agoYou could do: var exists = ~someStringOrArray.indexOf(searchTerm); if(exists){...} or // If exists do... if(~someStringOrArray.indexOf(searchTerm))