Hello, I met the code, I can not understand the use of the bitwise operator ~ in checking for the presence of a substring in a string.

/*Создайте функцию addClass(obj, name), которая добавляет в список класс name, но только если его там еще нет*/ function addClass(obj, name) { var classes = (obj.className) ? obj.className.split(' ') : []; if (~obj.className.indexOf(name) !== -1) classes.push(name); obj.className = classes.join(' '); } 

    1 answer 1

    The operation of the operator tilde ~ can be described by the formula

     -(N + 1) 

    where N is the number before the tilde.

    Therefore, for example, var a = ~15; console.log(a); var a = ~15; console.log(a); will give -16

    In your case, it turns out that the result of indexOf can return a number or -1. With the help of a tilde this is converted to -1 or to -(N + 1) respectively. Well, then it will be compared (more precisely, it will be checked for the inequality minus one), which will give true or false well, and, accordingly, the conditional operator will work or not

    In general, the conditional operator with indexOf could be replaced by

     if (~obj.className.indexOf(name)) 
    • 2
      Tilda is great for bringing horror to your colleagues with ninjutsu constructions like return !! ~ obj.className.indexOf (name); , on the one hand, everything seems to be clear, on the other hand, not everyone will read it) - Duck Learns to Take Cover
    • @ DUCK LEARNING, but after all !! tilde is not needed. there and without it will lead to a boolean, so in this case it is redundant - Alexey Shimansky
    • It is given but not the meaning. !! - 1 - true. And we want to false if not found. That is, obj.className.indexOf (name)! = -1 in simple words - Duck Learns to Take Cover