10
(function () {
    var names = [];
    return function (name) {
        addName(name);
    }
    function addName(name) {
        if (!~names.indexOf(name))//
            names.push(name);
    console.log(names);// ["linkFly"]
    }
}())('linkFly');

sometimes i have seen this logical,what is it mean ? thanks ~

simotophs23
  • 195
  • 1
  • 6
  • 1
    You can take what meaning you like from it. I like to think it means the writer of the code didn't think that anyone else would ever have to read their code. – bhspencer Feb 10 '15 at 03:40
  • I have know how it is work and it's a bad practice thanks all~~~ – simotophs23 Feb 10 '15 at 04:18

2 Answers2

20

tl;dr

indexOf returns -1 when an element cannot be found in an array. Therefore, the if statement is checking if name could not be found in names. !~-1 ==> true

Longer version:

The tilde (~) operator (bitwise NOT) yields the inverted value (a.k.a. one’s complement) of a. [Source] For example, ~-1 === 0. Note that 0 == false and !0 === true. indexOf returns -1 when an element cannot be found in an array. Therefore, we can use !~-1 === true to find out if indexOf could not find name in names (i.e. returned -1).

My opinion:

As you can see, using these obfuscated or "clever" techniques without comments can really confuse the reader. If you do love these techniques, please document what your line(s) of code are doing for the sake of the readers!

rgajrawala
  • 1,868
  • 1
  • 19
  • 34
  • only !~(-1) return ture ? – simotophs23 Feb 10 '15 at 03:25
  • Would you consider this to be bad practice. It isn't exactly self documenting code. – bhspencer Feb 10 '15 at 03:26
  • 3
    That's a simplistic explanation, the tilde flips the bits, and the `!` reverses that to a boolean, even if it's basically the same as `names.indexOf(name) != -1`, this answer hardly explains the behaviour in any meaningful way ? – adeneo Feb 10 '15 at 03:27
  • 6
    On a side note: This code is unnecessary "clever". Saving a few characters is not worth the confusion it's causing. I say it is bad practice. – kapex Feb 10 '15 at 03:29
  • @simotophs23 Yes, because zero is the only falsy number. Note that `~-1 === 0`. – rgajrawala Feb 10 '15 at 04:46
0

! (Logical NOT) Returns false if its single operand can be converted to true; otherwise, returns true.

For all integer operands except -1, the net operand after applying the ~ operator for the ! operator would be truthy in nature resulting in FALSE. -1 is special because ~(-1) gives 0 which is falsy in JavaScript. Adding the ! operator gives us the only TRUE.