Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the " !~" mean in javascript [duplicate]

Tags:

javascript

(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 ~

like image 339
simotophs23 Avatar asked Feb 10 '15 03:02

simotophs23


1 Answers

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!

like image 140
rgajrawala Avatar answered Oct 11 '22 07:10

rgajrawala