Yeah Yeah - 27 days ago 8
Javascript Question

Issue while using ?: operator inside Array.prototype.findIndex

Example:



var img = $('img');
var div = $('div');

var arr = ['1', '2', '3'];

console.log(arr.findIndex(x => x === img.length ? img.prop('id') : div.prop('id')));

console.log(arr.findIndex(x => x === (img.length ? img.prop('id') : div.prop('id'))));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<div id="2"></div>





Output:


0

1


The first case:

x === img.length ? img.prop('id') : div.prop('id')


If it compared
x
to
img.length
. I don't understand that why did it return
0
?

img.prop('id')
returns
undefined
and
div.prop('id')
returns
2
, why did it log
0
?

The second case:

x === (img.length ? img.prop('id') : div.prop('id'))


it got the id of the div tag before comparing to
x
. That's okay.

Please correct me. Thank you!

Answer Source

x will always be a string in your code, and img.length will be a number, so they will never be strictly equal (===).

So it gets evaluated as:

(x === img.length) ? img.prop('id') : div.prop('id')
(false           ) ? img.prop('id') : div.prop('id')
                                      div.prop('id')
                                      2

findIndex waits for a truthy value, and div.prop('id') is 2, which is truthy. It returns this on the first index, which is why it returns 0.