(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 ~
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With