5

I was wondering, say I had some thing like the following:

console.log(element.find('div').eq(3).text().indexOf('whatever'));

bearing in mind that element is defined and the console is logging a value of 32 (or anything that isn't -1) what would be the best way of converting the result into a Boolean so my console.log either outputs true or false

Thanks in advance.

Mike Sav
  • 14,805
  • 31
  • 98
  • 143

2 Answers2

15

The answer above will work, however if you are as nerdy as I, you will far prefer this:

console.log(~element.find('div').eq(3).text().indexOf('whatever'));

The obscure '~' operator in javascript performs the operation "value * -1 - 1", e.g. ~-2 === 1. The only use case I have ever had for this is in converting the "not found" -1 from ".indexOf()" into "0" (a falsey value in javascript), follow through and see it will convert an index found at position "0" to "-1", a truthy value.

tldr:

~[1,2,3].indexOf(0) // => 0
!!~[1,2,3].indexOf(0) // => false

~[1,2,3].indexOf(1) // => -1
!!~[1,2,3].indexOf(1) // => true
SirRodge
  • 594
  • 5
  • 8
  • 1
    You may want to revise your answer, as `~` is not really obscure. It is the bitwise NOT operator, which switches all 1s to 0s in the binary representation of your number. since -1 is `111....1` in binary, it turns to `000....0` which can be cast to `false`. ... better explanation in this answer: https://stackoverflow.com/questions/4295578/explanation-of-bitwise-not-operator – Marconius Jan 09 '18 at 14:47
  • 1
    From my tests, both this solution and the accepted solution run at roughly the same time. Ergo, if performance is your concern; it needn't be - choose the solution you prefer for readability. – JustCarty Dec 19 '18 at 16:11
11
console.log(element.find('div').eq(3).text().indexOf('whatever') > -1);
johnnycardy
  • 3,049
  • 1
  • 17
  • 27