Skip to content

Commit 3c7952f

Browse files
committed
fixes ~n
1 parent d303295 commit 3c7952f

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

1-js/05-data-types/03-string/article.md

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,8 @@ if (str.indexOf("Widget") != -1) {
305305
}
306306
```
307307

308-
````smart header="The bitwise NOT trick"
308+
#### The bitwise NOT trick
309+
309310
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.
310311

311312
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)
321322
*/!*
322323
```
323324

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`.
325326

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.
327328

328329
People use it to shorten `indexOf` checks:
329330

@@ -338,7 +339,10 @@ if (~str.indexOf("Widget")) {
338339
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.
339340

340341
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).
342346

343347
### includes, startsWith, endsWith
344348

0 commit comments

Comments
 (0)