Tuesday 5 May 2015

lodash _.find() seemingly not working

lodash is an excellent JavaScript library that you should probably be making use of.  Before we go any further, I should make it clear that the find() method works just fine.

We're using lodash on a legacy project and I've made the same mistake with the find() method a couple of times now, so thought I'd document this amateurish mistake.

I find JavaScript's loose typing can lead to lazy practice.  You get used to automatic type conversion and forget to think about data types and data type conversion. Take this example:

HTML
<input type="text" id="myInput" />
<button onclick="printName()">Print Name</button>


JavaScript
var listOfPeople = [{name: 'dave', id: 1}, {name: 'john', id: 2}, {name: 'lisa', id:3}];
function printName() {
    var personId = document.getElementById("myInput").value;
    var person = _.find(listOfPeople, {'id': personId});
    alert (person.name);   
}


Simple stuff: we're reading the personId and then using _.find() to retrieve the person object from our internal data structure.  But it doesn't work, nothing is alerted!

Initially you might wrongly conclude _.find() is not working.  However, the issue is document.getElementById("myInput").value returns a string primitive.  The data structure stores the ids as number primitives.  The _.find() method does a strict comparision (===) and therefore it doesn't matter what the values are, a string primitive will never === a number primitive.  The solution is easy, change this line to:

var personId = parseInt(document.getElementById("myInput").value);

We're now comparing numbers with numbers and it works as expected.

JSFiddle: https://jsfiddle.net/ctwuh6e1/3/