You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/05-data-types/03-string/article.md
+8-4Lines changed: 8 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -305,7 +305,8 @@ if (str.indexOf("Widget") != -1) {
305
305
}
306
306
```
307
307
308
-
````smart header="The bitwise NOT trick"
308
+
#### The bitwise NOT trick
309
+
309
310
One of the old tricks used here is the [bitwise NOT](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT)`~` operator. It converts the number to a 32-bit integer (removes the decimal part if exists) and then reverses all bits in its binary representation.
310
311
311
312
For 32-bit integers the call `~n` means exactly the same as `-(n+1)` (due to IEEE-754 format).
@@ -321,9 +322,9 @@ alert( ~-1 ); // 0, the same as -(-1+1)
321
322
*/!*
322
323
```
323
324
324
-
As we can see, `~n` is zero only if `n == -1`.
325
+
As we can see, for 32-bit integers `~n` is zero only if `n == -1`.
325
326
326
-
So, the test `if ( ~str.indexOf("...") )` is truthy that the result of `indexOf` is not `-1`. In other words, when there is a match.
327
+
So, the test `if ( ~str.indexOf("...") )` is truthy only if the result of `indexOf` is not `-1`. In other words, when there is a match.
327
328
328
329
People use it to shorten `indexOf` checks:
329
330
@@ -338,7 +339,10 @@ if (~str.indexOf("Widget")) {
338
339
It is usually not recommended to use language features in a non-obvious way, but this particular trick is widely used in old code, so we should understand it.
339
340
340
341
Just remember: `if (~str.indexOf(...))` reads as "if found".
341
-
````
342
+
343
+
Technically speaking, numbers are truncated to 32 bits by `~` operator, so there exist other big numbers that give `0`, the smallest is `~4294967295=0`. That makes such check is correct only if a string is not that long.
344
+
345
+
Right now we can see it only in the old code, as modern JavaScript provides `.includes` method (see below).
0 commit comments