Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert result of .indexOf to a Boolean using JavaScript or jQuery

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.

like image 343
Mike Sav Avatar asked Jan 03 '14 15:01

Mike Sav


People also ask

How do you convert boolean to data?

We convert a Number to Boolean by using the JavaScript Boolean() method. A JavaScript boolean results in one of the two values i.e true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e “true” or “false”.

What does indexOf return in JavaScript?

JavaScript String indexOf() The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.

Does indexOf return a Boolean?

prototype. indexOf() to find out whether the element is present in the array or not. But it doesn't return a boolean. It returns the first index of the element found in the array, or it will return -1 (which represents that the element is not found).

Is 1 true in JavaScript?

0 and 1 are type 'number' but in a Boolean expression, 0 casts to false and 1 casts to true . Since a Boolean expression can only ever yield a Boolean, any expression that is not expressly true or false is evaluated in terms of truthy and falsy. Zero is the only number that evaluates to falsy.


2 Answers

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
like image 109
SirRodge Avatar answered Sep 28 '22 23:09

SirRodge


console.log(element.find('div').eq(3).text().indexOf('whatever') > -1);
like image 36
johnnycardy Avatar answered Sep 29 '22 00:09

johnnycardy