1

I'm using and adapting the MVC example included in the Express.js repository.

In one of the modules, there's a JavaScript construct I'm not familiar with. The intent is to iterate through keys on an object and skip a few that are "reserved", but I don't understand what is happening with the tilde from a JavaScript perspective.

for (var key in obj) {
    if (~['name', 'prefix', 'engine', 'before'].indexOf(key)) continue; 
}

I'm reading it's a Bitwise NOT operator, but would appreciate an explanation in layman's terms of what that means, as well as what it's doing in this particular example.

1 Answers1

0

indexOf returns -1 if not found. ~-1 is 0, i.e. false. So the whole things means: if key is found in the array, do continue.

buff
  • 2,063
  • 10
  • 16
  • Can you add some color as to why ~-1 is 0? I am trying to read up on this, but not clear on how negative numbers are treated. Is `~-X==0` ? –  Jun 29 '14 at 19:43
  • @JDMaresco: `NOT x = −x − 1`, ie `-(-1)-1 == 0` – elclanrs Jun 29 '14 at 19:52
  • `-1` is a signed integer composed of 32 bits. Each of them is one. Bitwise negation turns each of them to zero. An integer of all zeros is zero. See this http://stackoverflow.com/a/9954783/328977, assign `my_int = -1` and try yourself. – buff Jun 29 '14 at 20:00
  • 1
    It's quite the opposite: the whole thing means that if `key` is found in the array, continue. – axelduch Jun 30 '14 at 13:14
  • @aduch: You are right! I'll fix the answer. Thanks! – buff Jun 30 '14 at 13:17