0
(~$.inArray('orange', apple))

Can anyone explain what is the above code mean in jquery?

what is ~ and .inArray?

Kit Ho
  • 23,048
  • 42
  • 104
  • 150
  • 2
    jQuery inArray http://api.jquery.com/jQuery.inArray/ – Anton Dec 17 '13 at 10:47
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FOperators%2FBitwise_Operators – Arun P Johny Dec 17 '13 at 10:50
  • 1
    @Kevin, more like showing off and killing readability, if you ask me. – Frédéric Hamidi Dec 17 '13 at 10:52
  • @kevin, if you try it in a browser, you'll find that it flips between 0 and -1. which is interpreted properly as falsey and truthy respectively – mr rogers Dec 17 '13 at 10:55
  • 1
    @Kevin, that's actually a side effect of two's complement: it will map `-1` to `0`, `0` to `-1` and positive numbers to non-zero numbers. See [this answer](http://stackoverflow.com/a/9316724/464709) for details. – Frédéric Hamidi Dec 17 '13 at 10:55
  • I don't think this is a bad question after all... The code is not intuitive. – Kevin Bowersox Dec 17 '13 at 10:56
  • possible duplicate of http://stackoverflow.com/questions/8191531/what-does-mean-in-javascript – Anusha Dec 17 '13 at 10:57
  • @iJay it means "found in array", not found is `!~$.inArray()` – A. Wolff Dec 17 '13 at 10:58
  • 1
    @FrédéricHamidi i'm not sure comparing something to -1 is more readable than setting a sign before an evaluated expression. I mean do you find: `if($.inArray('orange', apple) !== -1)` more readable than just `if(~$.inArray('orange', apple))` but that's just my opinion. – A. Wolff Dec 17 '13 at 11:04

1 Answers1

2

It means nothing in jQuery as it is JavaScript.

~ is an operator that does something that you’d normally think wouldn’t have any purpose. It is a unary operator that takes the expression to its right performs this small algorithm on it (where N is the expression to the right of the tilde): -(N+1). See below for some samples.

console.log(~-2); // 1
console.log(~-1); // 0
console.log(~0);  // -1
console.log(~1);  // -2
console.log(~2);  // -3

So, unless you actually have an application that needs to run this algorithm on numbers

Source Taken from

inArray

Search for a specified value within an array and return its index (or -1 if not found).

so in combination if element not find on (~$.inArray('orange', apple)) it will return zero else index will be converted as above given series.

Community
  • 1
  • 1
Zaheer Ahmed
  • 26,435
  • 11
  • 70
  • 105